Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting an undefined data and the "Query data cannot be undefined" error

I am using Next.js to build a project for my portfolio. And, I am trying to use Tanstack query along with Axios to handle the API.

The problem is, I am getting an error while I'm trying to fetch the data. The data gets fetched from the API and I can see it when I console.log it inside the function. But when I try to access it outside the function, it returns undefined.

Here's my code for the function:

const Home = () => {

  const {data} = useQuery({
    queryKey: ['products'],
  
    queryFn: async () => {
      const res = await axios.get(
        'https://fakestoreapi.com/products'
      )
      const data = await res.data
      console.log(data)
      //can access data here
    }
  })
  
  console.log(data)
  //cannot access data here and returns undefined.

  return (
    <section>
      //some codes here
    </section>
  )
}

I am also getting this error in the console:

Query data cannot be undefined. Please make sure to return a value other than undefined from your query function. Affected query key: ["products"]

I have looked everywhere for the fix and found no clue what is causing this. Can someone help me fix this?

Side note: I can get the data when using a normal fetch request.

like image 667
Gaurav Tamang Avatar asked Jan 21 '26 14:01

Gaurav Tamang


1 Answers

The function you are passing as a value to queryFn is returning nothing, hence when it resolves, it returns undefined. This should work:

const Home = () => {
  const { data } = useQuery({
    queryKey: ["products"],
    queryFn: async () => {
      const res = await axios.get("https://fakestoreapi.com/products");
      return res.data;
    },
  });

  return <section>{/* some codes here */}</section>;
};
like image 83
yousoumar Avatar answered Jan 24 '26 04:01

yousoumar