Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delete an Item from Array not Rendering ReactJS Hooks

Tags:

reactjs

I am trying to delete an item from Array using the Index, I am Passing the Props from Parent to Child Component to perform this operation, now i can see the console log that it's getting deleted, but it's not rendering the component

I have Posted the code in SandBox, since it will get messy here

Link : https://codesandbox.io/s/jovial-burnell-qkl7r

like image 666
Logesh P Avatar asked Jan 24 '26 12:01

Logesh P


1 Answers

You are rendering data from props.listofapi but updating array, your changes don't get updated because you are changing the wrong array. .splice() removes/adds an item to/from array, you don't have to do setArray(...array, temp); but setArray(tempArray);

use useEffect to save the initial data to array.

const deleteHandler = id => {
  console.log(id);
  const tempArray = [...array];
  // removes item from tempArray
  tempArray.splice(id, 1); 
  setArray(tempArray);
  console.log("temp array", tempArray);
};

React.useEffect(() => {
  // data from props to array here
  setArray(props.listofapi);
}, [props.listofapi]);

and map array instead of props.listofapi

<TableBody>
      {array.map((row, index) => (
      ...

Example

like image 84
TenTen Peter Avatar answered Jan 29 '26 03:01

TenTen Peter



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!