The Dead Man
The Dead Man

Reputation: 5566

React Hooks: useQuery data are gone after page refresh

I am getting data from API using useQuery when I load the page data is returned, But when I refresh the page data is gone any idea why?

 const { isLoading, data } = useQuery("page-data", () => {
    return api.get(`/landing_pages/204`);
  });

  useEffect(() => {
      console.log("Page data", data); // when I refresh the page its undefined

  }, [])

Upvotes: 1

Views: 1271

Answers (1)

henk
henk

Reputation: 2838

The data is undefined as long as your query is loading. Your useEffect has an empty dependency array, so it is executed only one single time when the component gets mounted, but not when it is updated.

But data will be defined on the consecutive rendering only, thus when the component gets updated.

So to access it inside of the useEffect, you have to add the isLoading as a dependency and check for the loading to be completed.

 useEffect(() => {
         if(!isLoading){
          console.log("Page data", data); // when I refresh the page its undefined
         }
      }, [isLoading])

Upvotes: 3

Related Questions