简体   繁体   中英

How to update state (array of objects) with incoming object in Redux?

For example, current state is:

    {
     data: [
      {id: 1, number: 100},
      {id: 2, number: 200},
      {id: 3, number: 300}
     ]
    }

Action is:

   const action = (id, number) => {
    return {id: id, number: number}
   }

How to implement reducer that it meets the following requirements:

  1. If the state (array of objects) doesn't have an object with the same id as an incoming object - push the incoming object to the state;
  2. If the state has an object with the same id as an incoming object - update this object in state with number field value of an incoming object .

CASE 1:

//incoming object
{id: 4, number: 400}

//result
    {
     data: [
      {id: 1, number: 100},
      {id: 2, number: 200},
      {id: 3, number: 300},
      {id: 4, number: 400}
     ]
    }

CASE 2:

//another incoming object
{id: 2, number: 250}

//result
    {
     data: [
      {id: 1, number: 100},
      {id: 2, number: 250},
      {id: 3, number: 300},
      {id: 4, number: 400}
     ]
    }

Maybe it has a simple solution, but I can't find the right approach to solving this problem:) Also I would like to know what is the best practice in cases like this.

Thank you in advance

I changed your action to use the payload property, but if you want you can remove it. (It's more proper to have it)

 const reducer = (state, action) => { switch(action.type) { case 'UPDATE_OR_INSERT': return { data: [ ...state.data.filter(x => x.id !== action.payload.id), action.payload, ] } default: } return state; } console.log( reducer({ data: [ {id: 1, number: 100}, {id: 2, number: 200}, {id: 3, number: 300}, {id: 4, number: 400} ] }, { type: 'UPDATE_OR_INSERT', payload: {id: 2, number: 250}}));

How do you think of this solution?

const testState = {
    data: []
}

export default (state = testState, action) => {
    switch(action.type){
        case "SET_DATA":
            return [
                ...state.data.filter(d => d.id !== action.payload.id),
                action.payload,
            ];
        default:
            return state;
    }
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM