pazta
pazta

Reputation: 371

Add object to existing array in state

I have an application that uers lets create new tables, lets say I have the following state:

const initialState = {
  table: [{
    id: 1,
    item: {}
  }]
}

Now I want to add new objects to the item:

The reducer:

case types.ADD_ITEM:
    return {
      ...state,
      table: [...state.table, { item: action.item}],
      loading: false
    }

So after user adds new items in a table the state should look something like this:

table: [
// table with id 1
      {
        id: 1,
        item: {
          id: '1',
          data: 'etc'
        }
        item: {
          id: '2',
          data: 'blabla'
        }
      },
  // table with id 2
      {
       id: 2,
       item: {
        id: '1'
        data: 'etc'
       }
      },
 // etc
    ]

I think I have my reducer wrongly setup.. the tables are added correctly, but Items not.

Current format is:

table: [
      {
        id: 1,
        item: []
      },
      {
        item: {
          id: '1'

        }
      }
    ]

Upvotes: 0

Views: 33

Answers (1)

AdamGold
AdamGold

Reputation: 5051

I think you are trying to add the contents of action.item to your array. What you're currently doing is adding the contents as a new element. You can use the following to achieve your desired output:

case types.ADD_ITEM:
    return {
      ...state,
      table: [...state.table, { ...action.item }],
      loading: false
    }

Or if you want to get only the id field of the item, and store the item inside a item field:

case types.ADD_ITEM:
    return {
      ...state,
      table: [...state.table, { id: action.item.id, item: action.item }],
      loading: false
    }

Upvotes: 1

Related Questions