Reputation: 9625
I got a React/Redux app that receives posts from a server. So far, I got the RECEIVE_POSTS right in my reducer, which looks as follows:
function posts(
state = {
items: []
},
action
) {
switch (action.type) {
case RECEIVE_POSTS:
return Object.assign({}, state, {
items: action.posts,
})
case ADD_POST:
default:
return state
}
}
Now for the other cases, I am struggling with the Object.assign
syntax. How would I update the state in the ADD_POST case , where a newly created post contained in action.post
is to be appended to the existing items?
Upvotes: 0
Views: 78
Reputation: 111
This is done assuming that a single post inside an array is being passed
function posts(
state = {
items: []
},
action
) {
switch (action.type) {
case RECEIVE_POSTS:
return Object.assign({}, state, {
items: action.posts,
})
case CREATE_POST:
return Object.assign({}, state, {
items: [...state.items, ...action.post]
})
default:
return state
}
}
Upvotes: 1
Reputation: 2684
Assuming CREATE_POST
refers to ADD_POST
based on receiving post data, it would look like this :
case CREATE_POST:
return {...state, items: state.items.concat(action.post)};
No need to use object assign since you can just concat
your post with the already existing posts from your state. As a reminder, concat
does not mutate state, it returns a new array with the added post
.
Upvotes: 2