0

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'

        }
      }
    ]
2
  • With this code you are adding an item into tables array. Commented May 20, 2019 at 13:05
  • just change to table: [...state.table, { ...action.item} ] Commented May 20, 2019 at 13:12

1 Answer 1

1

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
    }
Sign up to request clarification or add additional context in comments.

1 Comment

hmm, this actually creates a table with the items id + items objects, I need to add the action.item objects into the item object inside table array

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.