Home > Back-end >  How can i trigger an update from one Table to another Table in React Typescript
How can i trigger an update from one Table to another Table in React Typescript

Time:01-16

in React Typescript i have a parent component with two independant child components:

export const Editor = () => {
  return (
    <>
      <TableTotal />
      <hr />
      <TableDetail />
    </>
  );
};

And after some actions in TableDetail i have to completely reload data in TableTotal component. In TableTotal i have code like this:

 useEffect(() => {
    getData();
  }, []);

where getData is a function with fetch from the server.

How can i told the TableTotal component to reload data from the TableDetail Component (calling the getData() function) ? I use React with Typescript. Thanks

CodePudding user response:

The concept you need to solve this is called lifting state up in the React documentation. You store the data shared by TableTotal and TableDetail inside Editor, and then pass the data to each child component as props. That way, if one component causes the data to change, the other one will re-render with the new data, too.

CodePudding user response:

There are 2 solutions out there. Either use the prop drilling method or take your app states to global (context/redux).

Prop Drilling: Initialize state in the Editor Component, if you change something in any component, make that state dependency of the useEffect and it will call getData() and re-render the components.

  •  Tags:  
  • Related