Updating a array inside object using immutableJS is not working

54 Views Asked by At

I am trying to add an object inside an array which is nested inside a object. The following is my structure

{
    id:'1',
    name:'test',
    contents:[
        {fruit:'banana'}
        {fruit:'apple'}
    ]
}

Now i am just trying to update the contents with {fruit:'pear'}. I am using react-redux-boiler plate. And i am having issue trying to update the contents. Here is what i have tried :

const initialState = fromJS({
  data: {
    content: []
  }
});

function projectReducer(state = initialState, action) {
  switch (action.type) {
    case LOAD_DATA:
      return state
        .set('loading', true)
        .set('error', false)
        .setIn(['data', 'contents'], false);
    case LOAD_DATA_SUCCESS:
      return state
        .setIn(['data', 'contents'], action.data)
        .set('loading', false);
    case ADD_CONTENT:
      return state
        .set('loading', true)
        .set('error', false)
      // return return update(state[state.set(['data'],data)
    case ADD_CONTENT_SUCCESS:
      console.log('addContentSuccess');
      return state
        .updateIn(['data','contents'],list=>list.push({fruit:'pear'}))         //<<<<<THis is failing
        .set('loading', false)
        .set('error', false)
      break;
    default:
      return state;
  }
}

i get the error as push is not a function which is correct as list is the whole object ,is not list.contents.

Any suggestion or help or workaround is much appreciated ! Thanks in advance !

1

There are 1 best solutions below

2
On

It looks like you've made a typo, you forgot to put quotation-marks around contents, which results in it being undefined and therefore 'list' is actually 'data'.

I think your code should be:

return state
    .updateIn(['data', 'contents'], list => list.push({fruit:'pear'}))