2

Is it possible to re-render one or both of a component's children if one of them updates? I have a component that looks like this:

const ContributeBody = () => (
  <StyledContributeBody>
    <LastThreePages />
    <ContributeForm />
  </StyledContributeBody>
);

The ContributeForm component collects data and calls an API function that adds data to my Fauna DB Collection.

The LastThreePages component calls an API function that gets the last three pages from the Fauna DB Collection.

At present, it is necessary to hard reload the page to order to update LastThreePages.

I am looking for a way to reload LastThreePages after ContributeForm submits the data to the data to the Fauna DB Collection.

Currently, I am not using Redux or GraphQL. I am using FQL.

Is is a flux pattern the answer here?

Tithos
  • 1,191
  • 4
  • 17
  • 40

2 Answers2

0

As far as I know, react re-renders component when it's state or property changes. I guess passing some dummy property around would work (I didn't test this):

const ContributeBody = () => (
  const [rev, setRev] = useState((new Date()).valueOf());

  <StyledContributeBody>
    <LastThreePages rev={rev} />
    <ContributeForm onSuccess={() => {setRev((new Date()).valueOf());}} />
  </StyledContributeBody>
);

Call onSuccess when need to re-render

Gennady Dogaev
  • 5,902
  • 1
  • 15
  • 23
  • Great thought, but no dice. :( – Tithos Jan 14 '20 at 23:47
  • I also tried putting the functions from `LastThreePages' and 'ContributeForm' in the parent and passing the data down. Also... no dice. – Tithos Jan 14 '20 at 23:49
  • @Tithos your `useEffect` has an empty array as second parameter. That means it fires just on first render. You need to add `rev` property there (means "run when rev changed") or remove that empty array at all (means "run on every re-render" – Gennady Dogaev Jan 15 '20 at 00:05
0

My suggestion is that StyledContributeBody (or higher) manages the data reading and submitting, and then via React Context (recommended) or Redux or passing the data as props, you pass the data to the child components.

When the data is read and changes, you can trigger a refresh of the other data, which will trickle down to the child components.

dano
  • 5,640
  • 5
  • 27
  • 27