Home > OS >  why useState doesn't work with useEffect()?
why useState doesn't work with useEffect()?

Time:07-12

  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?

CodePudding user response:

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]);

CodePudding user response:

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]}
  • Related