TheMightyLlama
TheMightyLlama

Reputation: 1273

React useEffect is only updating one of the values

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 });
    });
  }
}, []);

Upvotes: 0

Views: 28

Answers (1)

Rahul Sharma
Rahul Sharma

Reputation: 10111

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,
      }));
    });
  }
}, []);

Upvotes: 3

Related Questions