Append/push in seamless immutable js - react js

465 views Asked by At

In Reducer for initial state I am using a seamless-immutable.

export const INITIAL_STATE = Immutable({
  foo:[],

})




function orderReducer(state = initialState, action) {
  console.log('reducer is runnig');

  switch (action.type) {
    case GET_MENU: {

      return state.foo.push("newData") // how to achive this <----
    }

    default:
      return state;
  }
}

How do I to push new data into the foo?

1

There are 1 answers

2
jsdario On

If you want to stick with ImmutableJS you can use new List() that has a push method. Here are the docs. There are a bunch of data sets with different APIs that always return immutable objects. You will need to start learning those.

However if you are looking for a familiar way to deal with immutability I'd recommend you to switch to Immer. It let's you use plain javascript to return immutable objects, so you don't need to learn any new APIs. Take a look here:

https://github.com/mweststrate/immer

I personally always use plain javascript with the spread operator. I find it comfortable, fast, without any extra libraries. Very verbose when you get use to the syntax:

const pushedArr = [...oldArray, newElement]
const mergedObj = {...objA, ...objB}

Now that you know some alternatives, find the way that fits you and your team the most.