3

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;
maxwellgover
  • 6,661
  • 9
  • 37
  • 63
  • nice code formatting :+1: – yadhu Nov 29 '16 at 13:12
  • you can use the same logic of delete and add the updated link there – maioman Nov 29 '16 at 13:12
  • Possible duplicate of [Replace array item with another one without mutating state](http://stackoverflow.com/questions/35362460/replace-array-item-with-another-one-without-mutating-state) – yadhu Nov 29 '16 at 13:20

1 Answers1

7

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)
    ],
};
CodingIntrigue
  • 75,930
  • 30
  • 170
  • 176
  • 2
    You may also want to look at some of the information in the ["Structuring Reducers'](http://redux.js.org/docs/recipes/StructuringReducers.html) section of the Redux docs. In particular, see the ["Immutable Update Patterns"](http://redux.js.org/docs/recipes/reducers/ImmutableUpdatePatterns.html) page. – markerikson Nov 29 '16 at 16:53