0

I have following component hierarchy :

Component Parent --> Component Child

Component A :

export const Parent = () =>{
    const handleDeleteRow = (index) = >{
         data.splice(index,1)
         setData(data)
    }

    return (
         <Child handleDeleteRow={handleDeleteRow} data={data}/>
    )
}

const Child = ({handleDeleteRow,data}) =>{

    return (
         <div>
              <button onClick={()=>handleDeleteRow(index)}>Delete</button>
              {
                data.map((element) =>{
                    {`${data.firstname} ${data.lastname}`}
                })
              }
         </div>
    )
}


Currently, When I click on delete button, element gets deleted from data, but UI is not getting updated. data(parent component state) is array elements which can have multiple array elements.

Akshay phalphale
  • 145
  • 3
  • 14
  • 1
    [`splice`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice) mutates state, state mutations bypass React's way of determining if it should re-render. Fix - don't mutate state. – Brian Thompson Apr 07 '22 at 13:54

1 Answers1

1

In React, you should not change state variable directly. data.splice(index,1) in your code. This must be a bug.

And you should use deep copy for slicing.

Here is the updated parent component.

export const Parent = () =>{
  const [data, setData] = useState([]);
  const handleDeleteRow = (index) = >{
    setData(prevData => {
      // deep copy!
      const newData = JSON.parse(JSON.stringify(prevData));
      newData.splice(index,1);
      return newData;
    });
  }

  return (
    <Child handleDeleteRow={handleDeleteRow} data={data}/>
  )
}

Liki Crus
  • 1,901
  • 5
  • 16
  • 27
  • This will fix the problem, and is technically a correct answer; however, parsing to and from JSON is both more verbose syntax and less performant that alternatives. Generally you would use spread syntax like `const newData = [...prevData]`. – Brian Thompson Apr 07 '22 at 14:02
  • @BrianThompson React prevents to mutate state variable. spread operator `[...prevData]` is a shallow copy! – Liki Crus Apr 07 '22 at 14:13
  • React does not prevent mutation. Spread *is* a shallow copy, but there are no nested mutations taking place, so a shallow copy is all that is required. – Brian Thompson Apr 07 '22 at 14:14