I have the following code.
import Post from "../post/Post";
import "./posts.scss";
import {useQuery} from "@tanstack/react-query";
import {makeRequest} from "../../axios";
//omitted code here
const {isLoading, error, data } = useQuery({
queryKey: ["posts"],
queryFn: () => {
makeRequest.get("/posts").then((res) => {
return res.data;
})
},
});
In the browser I am getting the following error:
Query data cannot be undefined. Please make sure to return a value other than undefined from your query function. Affected query key: ["posts"]
2
Answers
queryFn
should return the promise.You cant really fix it as data can always be undefined because before the promise resolves, data will always be undefined.
The only real way you can fix it is to give a default value to data
Though this isn’t the best way to do it as data would always be an empty array, even if there is an error.
What would probably be better is build out your component like this