child hooks not rerendering after changing state in parent hooks

Below are parent component and child component, I just want to update child component once changing state in parent component.

I am creating one table which is child component and passing data from parent to child, and triggering delete function from child to parent. Data is getting deleted in parent but not sending same to child.

Any help is appreciable!!

Parent

import React, { useState } from "react";
import Pagination from "./components/Pagination.js";
import { Table } from "./components/Table.js";
import { useEffect } from "react";
import "./App.css";

function App() {

  const [tableData, setTableData] = useState([]);

  useEffect(() => {
    fetch("https://jsonplaceholder.typicode.com/posts")
      .then(response => response.json())
      .then(data => setTableData(data))

  }, [])

  const deleteRowData = (id) => {
    tableData.map((row, ind) => {
      if (id === row.id) {

        console.log(id);
        tableData.splice(ind, 1);
        console.log(tableData);
        setTableData(tableData);
      }
    })

  }
  // console.log(tableData)
  return (
    <div className="App">
      <div className="container py-4">
        <Table tableData={tableData} deleteRowData={deleteRowData} />
      </div>
    </div>
  );
}

export default App;

Child

import react from "react";
import { useEffect } from "react";
export const Table = (props) => {
    console.log("table component");

    return (<div><table>
        <thead>
            <tr>
                <td>ID</td>
                <td>Title</td>
                <td>Edit</td>
                <td>Delete</td>
            </tr>
        </thead>
        <tbody>
            {props.tableData.map((row, ind) => {
                return (<tr key={row.id}>
                    <td>{row.id}</td>
                    <td>{row.title}</td>
                    <td>Edit</td>
                    <td onClick={() => props.deleteRowData(row.id)}>Delete</td>

                </tr>)
            })}
        </tbody>
    </table>

    </div>)

}

>Solution :

Problem is that you are modifying array and setting new state passing same array (reference to same array) and react by default does not re-render child data if state does not change as shallow comparison is made.

Instead modify deleteRowData. You need to create new array (in this case filter takes current array and and returns new array without modifying old one);

    const deleteRowData = (id) => {
        const updatedData = tableData.filter(row => row.id !== id);
        setTableData(updatedData);
    }

Leave a Reply