Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

useQuery function returns void and I don't know why

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading