I am learning react-query
and I meet some problems. I want to use the data
I get from fetching data by useQuery
, but I get data
as undefined
. Here is my code:
import React from "react";
import { useQuery } from "react-query";
import { fetchData } from "./providesData";
const Home = () => {
const {data} = useQuery("fetchData", fetchData, {
onSuccess: () => {
console.log("Get data!");
console.log(data); // undefined
}
});
return <div></div>;
};
export default Home;
But I see in react-query devtools
that the fetch is succeeded and the data
is here. So I think I do not access the data
in my onSuccess
callback properly. So how can we get access to the data
in the callback? I tried:
const query = useQuery("fetchData", fetchData, {
onSuccess: () => {
console.log("Get data!");
console.log(query.data); // undefined
}
});
but still no luck.
I read the documentation and found this:
onSuccess: (data: TData) => void
So I tried this in my code:
const {data} = useQuery("fetchData", fetchData, {
onSuccess: (data: TData) => {
console.log("Get data!");
console.log(data); // success
}
});
This time it works. But I do not understand why... And the code editor also warned me:
Type annotations can only be used in TypeScript files.ts(8010)
Can anyone show me the right way to do it? Thank you so much!
Here is a demo.