staxwell staxwell - 7 days ago 6
Javascript Question

How can I replace the value in an array using redux?

I'm trying to overwrite a specific value in my Redux state which is an array. I have gotten the index already and also the value of the new text. I'm just not sure about the best way of overwriting the previous text. Here is my reducer so far. The UPDATE_LINK is the one I'm having trouble with.

export function linkList(state = [], action) {
switch(action.type) {
case 'ADD_LINK':
var text = action.text;
console.log('Adding link');
console.log(text);
return {
...state,
links: [text, ...state.links]
};
case 'DELETE_LINK':
var index = action.index;
console.log('Deleting link');
return {
...state,
links: [
...state.links.slice(0, index),
...state.links.slice(index + 1)
],
};
case 'UPDATE_LINK':
var index = action.index;
var newText = action.newText;
console.log(action.newText);
console.log(action.index);
return {
...state,
// How do I update text?
}
default:
return state;
}
};

export default linkList;

Answer

You could use Array.protoype.map to return the existing entries where available and a new entry where the index matches:

var index = action.index;
var newText = action.newText;
return {
    ...state,
    links: state.links.map((existingLink, currentIndex) => index === currentIndex ? newText : existingLink)
}

Or, following your existing DELETE_LINK logic:

return {
    ...state,
    links: [
        ...state.links.slice(0, index),
        newText,
        ...state.links.slice(index + 1)
    ],
};