Home > other >  React useEffect is only updating one of the values
React useEffect is only updating one of the values

Time:12-31

I realise that there is most likely a very simple explanation for this, only I can't quite figure it out. I'm making to API calls getNarrativeReferences and getNarrativeHeaders these return two separate values which go into two arrays in searchState. The problem being that on page load only ever one or the other is updated. Rendering either the headers or references but never both.

Should I refactor the API to return both references and headers in the same request. Or can this be arranged such that both are indeed updated?

useEffect(() => {
  console.log("QueryParam Value: "   id);
  if (id) {
    getNarrativeReferences(id).then((response) => {
      setSearchState({ headers: searchState.headers, references: response });
    });
    getNarrativeHeaders(id).then((response) => {
      setSearchState({ headers: response, references: searchState.references });
    });
  }
}, []);

CodePudding user response:

Use function inside setState, to get prev state and merge that with new state.

useEffect(() => {
  console.log("QueryParam Value: "   id);
  if (id) {
    getNarrativeReferences(id).then((response) => {
      setSearchState((prev) => ({
        ...prev,
        headers: searchState.headers,
        references: response,
      }));
    });
    getNarrativeHeaders(id).then((response) => {
      setSearchState((prev) => ({
        ...prev,
        headers: response,
        references: searchState.references,
      }));
    });
  }
}, []);
  • Related