0
votes

In my parent component:

I have a boolean state: const [isLoading, setIsLoading] = useState<boolean>(true);

Which i send to a child component:

return (
 <OrganisationPersonsLister personsStripped={personsStripped} isLoading={isLoading} />
);


In my child component: i recieve the props
const OrganisationPersonsLister = React.memo((props: { isLoading: boolean }) => {

}

And depending on the boolean value i want it to render different components.

  return (
    <section className="org-person-lister">
      {
        (isLoading)
          ? <Spinner />
          : <PopTable title={"title"} columns={columns} data={personsStripped} />
      }
    </section>
  )

How i update the state in parent component:

const viewOrganisation = (orgId: string) => {
    const org = orgList.find(o => o.id === orgId);
    if (org !== undefined) {
      setIsLoading(true)
      setChosenOrg(org);
      PersonApi.fetchPersonsByOrganisationId(orgId).then(response => {
        console.log("fetchPersonByOrganisationId: ", response)
        setIsLoading(false)
        setPersonsStripped(response)
      }).catch(err => {
        console.error("Error occurred: ", err);
        setIsLoading(false)
        setPersonsStripped([])
      });
    }
  };

The issue is that it does this once on initial load and then remains to false in child component even if the state is updated in the parent component. How can i make the state/props sync?

1
can you show, how you are updating state in parentShubham Khatri
Parent is not using React.memo. State in parent component is done through a axios function.Arasto
Can you add the JSX as well of parent, where you render the child element?Utsav Patel
@UtsavPatel yes of course, updated.Arasto

1 Answers

0
votes

Try adding a useEffect (import it next to your useState) that calls setIsLoading. Pseudo code below

useEffect(() => {
  if(...){
   setIsLoading(true)
   ...
  } else {
   setIsLoading(false)
  }
}, [var1, ...])

As a second argument to useEffect you can add the variable upon which change you want to trigger the effect and thus the state update