1

I want to add a post to an array of posts in the reducer. Normally I would just do this:

CREATE_NEW__POST_SUCCESS: {
    return {
        ...state,
        fetchingPosts: false,
        error: null,
        posts: [...state.posts, ...action.payload],
        };

However my current project requires me to use Immutable.js With Immutable the state is set with .set() or .merge() or .update()

case CREATE_NEW_POST_SUCCESS: {
    return state
        .set('fetchingPosts', false)
        .set('posts', action.payload)
        .set('postsError', null);

This overwrites the whole array of posts with just one post object. I tried lots of things like

 .set('posts' ,[...state.posts, ...action.payload])

But no joy

jojojohn
  • 725
  • 2
  • 10
  • 19

2 Answers2

1

You can use updateIn similarly to the answer here.

case CREATE_NEW_POST_SUCCESS: {
    return state
        .set('fetchingPosts', false)
        .updateIn(['posts'], posts => posts.push(action.payload))
        .set('postsError', null);
Moti Azu
  • 5,392
  • 1
  • 23
  • 32
  • this looks perfect, thank you. Still can't get it to work for some reason.I'll keep looking around for what I am doing wrong – jojojohn Apr 01 '19 at 11:42
0

I think state.merge() and concat() could work here:

case CREATE_NEW_POST_SUCCESS: {
    return state.merge({
        fetchingPosts: false,
        posts: state.get('posts').concat(action.payload),
        postError: null,
    })
}
Nandito
  • 11
  • 1