Reputation: 1760
In my application i am displaying person data. I have a scenario where I can input new person. So far I have got this: Reducer:
export default function (state = [], action) {
console.log("Reducing");
switch (action.type) {
case 'ADD':
console.log("ADDING!");
return action.payload;
break;
}
return state;
}
Action:
export const addPerson = (person) => {
console.log("addPerson Action Fired! ", person);
return {
type: 'ADD',
payload: person
}
};
I have a reducer with few person data which i am showing in my application but i am blocked at this point of adding new person. So far i can see my input in console log but can't figure out how can i add it to the state. Help would be very much appreciated.
This is the reducer where i am showing the data from.
export default function () {
return ["abc","def","ghi","jkl"]
}
Now i am displaying a list of these elements from the array(each are one person). When i add one it will be added with these persons and show me the updated list.
Upvotes: 1
Views: 77
Reputation: 1284
You should do the following in your reducer:
export default function (state = [], action) {
console.log("Reducing");
switch (action.type) {
case 'ADD':
return [
...state,
action.payload,
]
}
return state;
}
In this way, you add the person to your existing array. Otherwise you changes your current state
value from an array to an object.
Let's consider your person object value is the following and you dispatch it:
{
type: 'ADD',
payload: {
id: 1,
name: 'John Doe',
}
}
With your previous code, you would have the current value:
// First step
return action.payload;
// Second step
return { id: 1, name: 'John Doe' };
With the corrected code:
// First step
return [
...state,
action.payload,
]
// Second step
return [
...[],
{ id: 1, name: 'John Doe' },
]
// Third step
return [{ id: 1, name: 'John Doe' }];
Upvotes: 2