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;
3
  • nice code formatting :+1: Commented Nov 29, 2016 at 13:12
  • you can use the same logic of delete and add the updated link there Commented Nov 29, 2016 at 13:12
  • Possible duplicate of Replace array item with another one without mutating state Commented Nov 29, 2016 at 13:20

1 Answer 1

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)
    ],
};
Sign up to request clarification or add additional context in comments.

1 Comment

You may also want to look at some of the information in the "Structuring Reducers' section of the Redux docs. In particular, see the "Immutable Update Patterns" page.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.