Skip to content

[Typescript] How to pass the type for the error using useQuery? #934

Answered by alinjie
cant89 asked this question in General
Discussion options

You must be logged in to vote

Hi!

The error type can be set like this

interface Todo {
  userId: number;
  id: number;
  title: string;
  completed: boolean;
}

function useTodos(): QueryResult<Todo[], Error> {
  return useQuery("todos", async () => {
    const response = await fetch("https://jsonplaceholder.typicode.com/todos");

    if (!response.ok) {
      throw new Error("Failed to fetch!");
    }

    return await response.json();
  });
}

If the function throws the error variable will be of type Error, as specified in QueryResult.

Hope this helps!

Replies: 3 comments 2 replies

Comment options

You must be logged in to vote
2 replies
@cant89
Comment options

@MAb540
Comment options

Answer selected by cant89
Comment options

You must be logged in to vote
0 replies
Comment options

You must be logged in to vote
0 replies
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
5 participants