0

I'm currently importing this library:

import update from 'react-addons-update';

Here is my list:

[{id: 1, title: "some title"}, {id: 2, title: "some other title"}]

And my action:

action.type: 'change_title'
action.payload: [2, "some new title"]

The first parameter in action.payload refers to the id of the array I would like to change

Here is my reducer code:

export default (state = [], action) => {
  switch (action.type) {
    case 'change_title':
      return update(state, {
        0: {
          title: { $set: action.payload[1] }
        }
      });
    default:
      return state;
  }
};

As you can see, in it's current state my reducer function always changes the "title" value in the first array, but I would like to know: How can I specify which array to modify based on the "id" value?

1 Answer 1

1

You can do this at least two ways I think. First, using update(), you need to find the index of the item to update using Array.prototype.findIndex():

const index = state.findIndex(x => x.id === action.payload[0]);

case 'change_title':
  return update(state, {
    [index]: {
      title: { $set: action.payload[1] }
    }
  });

Or just using map:

case 'change_title':
    return state.map(item ==> {
        if(item.id !== action.payload[0]) {
            return item;
        }

        return {
            ...item,
            title: action.payload[1]
        };
    });    
Sign up to request clarification or add additional context in comments.

2 Comments

That doesn't work, because what that is doing is finding the array in position action.payload[0], as opposed to the array with id==action.payload[0]. So, for example, if action.payload[0] == 2 i get "Cannot read property 'title' of undefined" as there is not a third array
Works now. Thanks!

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.