Search code examples
react-nativeuse-effectuse-state

why useState doesn't work with useEffect()?


    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?


Solution

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