1
    const [dataSortArray, setDataSortArray] = useState([]);
   
     // seeAllFeeds
     const { data, loading, refetch, fetchMore } = useQuery(SEE_ALL_FEEDS_QUERY, {
       variables: {
         offset: 0,
       },
     });
   
     useEffect(() => {
       if (!loading) {
         refetch();
         console.log(data);
         setDataSortArray(data);
         console.log("✅", dataSortArray);
       }
     }, []);

as you can see I use useQuery.

if loading is done, i refetch the query and console.log(data) then data contains some array.

and I put this array into dataSortArray using setDataSortArray. but when I console.log dataSortArray, it's empty.

✅ Array []

do you know why?

Bhavya Koshiya
  • 1,262
  • 2
  • 8
  • 22
Hyejung
  • 902
  • 1
  • 8
  • 22
  • 1
    Does this answer your question? [Why does calling react setState method not mutate the state immediately?](https://stackoverflow.com/questions/30782948/why-does-calling-react-setstate-method-not-mutate-the-state-immediately) – Dominic Jul 11 '22 at 17:54
  • Question: is that `useQuery` hook you are using coming from `react-query` or any other library? – ivanatias Jul 11 '22 at 18:04
  • I think it's from ```apollo``` for ```GraphQL``` – Bhavya Koshiya Jul 12 '22 at 04:33

2 Answers2

0

put loading into dependency array it will invoke every time value of loading is change passing Empty array [] as dependency array means it will render only once

  useEffect(() => {
    if (!loading) {
      refetch();
      console.log(data);
      setDataSortArray(data);
      console.log("✅", dataSortArray);
    }
  }, [loading]);
Bhavya Koshiya
  • 1,262
  • 2
  • 8
  • 22
  • This may result in an infinite loop. Once initial load is done, the loading state will be updated from "True" to "False", which then will trigger another refetch that will change the loading state from "False" to "True". – Ziwon Jul 12 '22 at 04:42
  • if you don't want to refetch after loading is false then don't put it there or is there some logic for that? – Bhavya Koshiya Jul 12 '22 at 05:04
0

As @Dominic have pointed out in the question's comments (with a relevant link to another SO thread), useState is not effective immediately. So if you call setState on varA and console.log immediately afterwards, the varA won't be in the latest state you would expect.

I would suggest handling the state of dataSortArray in a separate useEffect.

  useEffect(() => {
    if (!loading) {
      refetch();
      console.log(data);
      setDataSortArray(data);
    }
  }, []);

  // Log dataSortArray when processing for setDataSortArray is completed by React.
  useEffect(() => {
    console.log(dataSortArray)
  }, [dataSortArray]}
Ziwon
  • 589
  • 6
  • 15