1

I'm using react-query's useQueries to define a custom hook useArtists:

type SuccessResponse = {
  artist: {
    name: string
  }
};


const fetchArtist = async (artistId: string): Promise<SuccessResponse> => {
  const response = await axios.get(`/artists/${artistId}`);

  if (response.status !== 200) {
    throw response.data.error ?? "Unknown error";
  }

  return response.data;
};


export const useArtists = (artistIds: string[]) => {
  return useQueries({
    queries: artistIds.map((artistId) => {
      return {
        queryKey: ["artists", artistId],
        queryFn: () => fetchArtist(artistId),
      };
    }),
  });
};

The inferred return type of useArtists is UseQueryResult<SuccessResponse, unknown>[].

How could I add the return type of the error, which is string, so that the return type becomes UseQueryResult<SuccessResponse, string>[]?

1
  • I was hoping useQueries might let you specify the success return type as generics but it doesn't appear as though. I tried to get this running on stackblitz without success: stackblitz.com/edit/react-ts-yacnui?file=App.tsx Commented Oct 5, 2022 at 11:14

1 Answer 1

4

You can provide types to useQueries by annotating queries you're passing to useQueries. In your example, this can be done by passing a generic to the .map itself:

type Artist = { name: string }

export const useArtists = (artistIds: string[]) => {
  return useQueries({
    queries: artistIds.map<UseQueryOptions<Artist[], Error>>((artistId) => {
      return {
        queryKey: ["artists", artistId],
        queryFn: () => fetchArtist(artistId),
      };
    }),
  });
};

UseQueryOptions can be imported from @tanstack/react-query, and it's the

Here's a working TypeScript Playground.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.