reidospeedo
reidospeedo

Reputation: 33

state of component keeps reverting back to it's original state

I have a component (DataGrid) with the following state:

    const [rows, setRows] = useState([
        { id: 1, lastName: 'Snow', firstName: 'Jon', status: 'Sold'},
        { id: 2, lastName: 'Lannister', firstName: 'Cersei', status: 'Quoted No Contact'},
    ])

Then I have a function that updates this state using "setRows"

const statusHandleChange = (e ,id) => {
      setRows(rows.map((row) => row.id === id ? {...row, status: e.target.value}: row))
    };

Basically, when you update the "status" field on a row in the grid it updates the corresponding status within the rows state.

It works great on the first update of a status to where if I changed the second row (id: 2) to 'Sold' then the state would console.log out to this:

{ id: 1, lastName: 'Snow', firstName: 'Jon', status: 'Sold'},
{ id: 2, lastName: 'Lannister', firstName: 'Cersei', status: 'Sold'}

BUT once I change another row, say row 1 (id: 2) to status: 'Interested', then the previous row I updated reverts back to it's original state.

{ id: 1, lastName: 'Snow', firstName: 'Jon', status: 'Interested'},
{ id: 2, lastName: 'Lannister', firstName: 'Cersei', status: 'Quoted No Contact'} //status switched back to 'Quoted No Contact' instead of the 'Sold' value I originally changed it to

This pattern of the previous row always reverting back to it's original state continues everytime I update a status. What am I doing wrong here?

Upvotes: 3

Views: 426

Answers (1)

Drew Reese
Drew Reese

Reputation: 202575

You haven't shown how you attach/call statusHandleChange but my guess is that you should use a functional state update anyway since the next state array depends on the state array from the previous state. This avoids any stale state enclosures in callbacks.

const statusHandleChange = (e ,id) => {
  setRows(rows => rows.map((row) => row.id === id ? 
    {
      ...row,
      status: e.target.value
    } : row
  ))
};

Upvotes: 1

Related Questions