D.R D.R - 9 days ago 5
React JSX Question

How can I update an object inside array of state?

So, I have a state of tables.

const initialState = {
allTables: [],
fetching: true,
tableId: {},
};


allTables is a state that has many objects of table.

allTables: Array[16]


and each object has id, current_order, type of table.

{
id: 1
type: "main"
current_order: null
}


So, now what I have is when a user clicks a table, it creates order. What I want to add is that when a user clicks a table, it sends order_id to the reducer, and update the current_order of table object.

case Constants.TABLE_IS_BUSY:
return { ...state, tableId: action.id }

case Constants.TABLES_NEW_ORDER_CREATED:
return Object.assign({}, state, {
tables: state.allTables.map((id) => {
if (state.allTables.id === state.tableId) {
return Object.assign({}, {
state.allTables.current_order: action.order
})
}
return state
})

})


So in order to do that, I made reducer like above. When you click table, it triggers TABLE_IS_BUSY and TABLES_NEW_ORDER_CREATED. For TABLE_IS_BUSY, i get table_id of table that a user clicked and change value of tableId of state. But for TABLES_NEW_ORDER_CREATED, it doesn't change the value of current_user... How can I do this correctly?

Thanks in advance..

Answer

Shouldn't you have something like:

case Constants.TABLES_NEW_ORDER_CREATED:
        return Object.assign({}, state, {
            tables: state.allTables.map((table) => {
                if (table.id === state.tableId) {
                    return Object.assign({}, table, {
                        current_order: action.order
                    })
                }
                else {
                   return Object.assign({}, table)
                }
            })
        })
Comments