Arasto
Arasto

Reputation: 491

Render child component props on parent state update

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?

Upvotes: 0

Views: 141

Answers (1)

Slim
Slim

Reputation: 683

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

Upvotes: 0

Related Questions