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.
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>;
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With