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:
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.