0

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 !

Sijan Shrestha
  • 2,136
  • 7
  • 26
  • 52
  • I'm guessing that content is not `List` after `LOAD_DATA_SUCCESS`. Change it to `.setIn(['data', 'contents'], List(action.data))` – soupette Oct 04 '18 at 16:28

1 Answers1

0

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'}))
Remco
  • 58
  • 5
  • Ah, sorry my bad, actually in the original code, its 'content' i just typed here and it is a mistake , Let me update the code – Sijan Shrestha Sep 29 '18 at 19:02
  • Hmm, then it seems there might be a problem with your Redux code because when I run the ImmutableJS code only, it seems to work: https://codepen.io/Risc12/pen/QZbjdY Is it maybe that the initialState defines 'content' instead of 'contents'? – Remco Sep 30 '18 at 20:55