Reputation: 55
this is my reducer function :
export default (posts = [], action) => {
switch (action.type) {
case FETCH_ALL:
return action.payload;
case LIKE:
return posts.map((post) => (post._id === action.payload._id ? action.payload : post));
case CREATE:
return [...posts, action.payload];
case UPDATE:
return posts.map((post) => (post._id === action.payload._id ? action.payload : post));
case DELETE:
return posts.filter((post) => post._id !== action.payload);
default:
return posts;
}
};
in
case CREATE:
return [...posts, action.payload];
what i have understood so far is that reducer function gets old state and new state . old state is represented by 'posts'
and new state is represented by 'action.payload'
...now what i do not understand is that what is [...posts, action.payload]
?
what are those three dots ? why there are square brackets ? what does reducer function returns ? what is happening here ? i am a java programmer , i can't understand anything here
Upvotes: 0
Views: 261
Reputation: 55
i have understood everything .
reducer function is getting two parameters (posts = [], action)
:
first one is old state and the second parameter is action object which includes type and new data ...this reducer function returns a new state by adding my new data into old state
in this
case CREATE:
return [...posts, action.payload];
these ...
three dots are spread syntax which can be understood completely by going to the following link given by chellappan in comment section :
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax
[]
square brackets denote an array which is our new state.
Upvotes: 1