Redux - modifying state of a nested array of objects

Viewed 53

So my Redux state should look something like this structure like this (of course there is nothing in the columns array, but I think this would be easier to understand)

columns: [
{id:1, title:'Column Title', items:['A1', 'B1', 'C1', 'D1' ]},
{id:2, title:'More Column Title',  items:['A1', 'B1', 'C1',  ]},
{id:3, title:'More Column Title',  items:['A1', 'B1', 'C1',  ]},
{id:4, title:'More Column Title',  items:['A1', 'B1', 'C1',  ]},
{id:5, title:'More Column Title',  items:['A1', 'B1', 'C1',  ]},
{id:6, title:'More Column Title',  items:['A1', 'B1', 'C1',  ]},]

What I want to do is add or modify elements in the items array but for a specific column individually, not all of them at once, I tried mapping and identifying a column by id but I failed to do something right and it results in a lot of errors. This is my last attempt, so the console log looks fine but I have no idea how to modify the state the same way.

case "ADD_ROWS":
  Object.assign({}, state, { 
    columns: [
        ...state.columns, 
        state.columns.map(col => { 
            if (col.id === action.payload.id) { 
                const items = col.items; 
                const newArray = col.items.concat(Array(10).fill())
                console.log(newArray); 
            } 
        }) 
    ] 
}); 
1 Answers

I'm not entirely aware if this how good using deeply nested data structures is for maintainability. However I managed to solved my issue using immutability-helper

So for my particular case the solution looks like this:

 case "ADD_ROWS":
  return update(state, {
    columns: columns =>
      update(columns || [], {
        [action.payload.id-1]: columnOne =>
          update(columnOne || {}, {
            items: items => update(items || [], { $push: Array(10).fill() })
          })
      })
  });

Hope this helps whoever is going through a similar immutability hell as I was.

Related