I wrote a function to fetch a user. And I return the user. But when I call the function with TanstackQuery the data is undefinded. When I add a return statement in the useQuery() function it works.
Here is my code that works:
export const getUserById = async (userId: string) => {
try {
const response = await axios.get(`${API_URL}/user/${userId}`);
return response.data;
} catch (err) {
console.log(err);
}
};
const { data = [], isSuccess } = useQuery({
queryKey: ['user'],
queryFn: async () => {
if (userId) {
const user = await getUserById(userId);
return user;
}
},
enabled: !!userId,
});
But this doesn't work:
const { data = [], isSuccess } = useQuery({
queryKey: ['user'],
queryFn: () => {
if (userId) {
getUserById(userId);
}
},
enabled: !!userId,
});
Because that's how the library tells you to use it:
queryFn: (context: QueryFunctionContext) => Promise<TData>
- Required, but only if no default query function has been defined See Default Query Function for more information.
- The function that the query will use to request data.
- Receives a QueryFunctionContext
- Must return a promise that will either resolve data or throw an error. The data cannot be undefined.