I am facing a problem with react queries in React with typescript template . It seems that useQuery returns nothing even though I do return data of certain type from it.
const { data } = useGetCommentsQuery(id as string, '1', '5');
I am calling the function (code block above) that wraps useQuery in my TSX component and when I hover over ‘data’ in VSCode I get the following message: Property 'data' does not exist on type 'void'.ts(2339). Bellow are useQuery function and axios api call respectively.
export const useGetCommentsQuery = (
movieId: string,
page: string,
limit: string
) => {
useQuery<ICommentPaginated | IError>(
[QUERRY_KEYS.COMMENTS] as QueryKey,
async () => {
const data = await commentsService.getComments(movieId, page, limit);
return data;
}
);
};
While hovering over returned ‘data’: const data: IError | ICommentPaginated
While hovering over ‘useGetCommentQuery’: const useGetCommentsQuery: (movieId: string, page: string, limit: string) => void – It does say ‘void’ indeed, but why?
class CommentsService {
async getComments(movieId: string, page: string, limit: string) {
return await httpService.request<ICommentPaginated | IError>({
url: `/api/comments?movieId=${movieId}&page=${page}&limit=${limit}`,
method: 'GET',
});
}
}
export const commentsService = new CommentsService();
>Solution :
The problem is that your useGetCommentsQuery function returns nothing.
In your code, useGetCommentsQuery just calls useQuery but doesn’t return any value.
You can modify your useGetCommentsQuery function to look like this:
export const useGetCommentsQuery = (
movieId: string,
page: string,
limit: string
) => {
return useQuery<ICommentPaginated | IError>(
[QUERRY_KEYS.COMMENTS] as QueryKey,
async() => {
const data = await commentsService.getComments(movieId, page, limit);
return data;
}
);
};
This should fix the TypeScript error.