Search code examples
javascriptreactjsreact-state

Component only has access to array's old state


I'm working with React and I have a table that users can add and delete rows from. The table is made with an array of components. Each component/row has a trash can icon that when clicked executes the delete row function. It would seem that each component only has access to the old state of the array/table, and so deleting doesn't work correctly. Any ideas how I could fix this issue?

An example of a component in the useState array that makes up this table:

<Row
  className={className}
  columns={columns}
  text={text}
  key={key}
  keyProp={key}
  deleteFunction={() => removeRow(key)}
/>

The delete function that is a prop for every row/component in the array:

function removeRow(key) {
  setMeals(meals.filter(i => i.props.keyProp !== key));
  // This should only remove the one row which had its trash can icon clicked.
  // If there's 10 rows and you click the trash can for row 4, rows 4-10
  // will be deleted.
  // If you click the trash can for row 7, rows 7-10 will be deleted and so on.
}

Solution

  • Give this a try, I am confident it will resolve the issue.

    function removeRow(key) {
    // This updates the previous meal array whenever there's a removal in the meal array
     setMeals((prevMeals) => {
        return prevMeals.filter((meal) => meal.props.keyProp !== key)
    })
    

    Also, improve your Delete function as shown below:

    <Row className={className} columns={columns} text={text} key={key} keyProp={key} deleteFunction={() => removeRow.bind(null, key)} />