Reputation: 7121
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;
Upvotes: 3
Views: 2307
Reputation: 78525
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)
],
};
Upvotes: 7