简体   繁体   中英

Typescript types for useQueries (react query)

I have something like:

// useMyList hook:

const allQueries = myList.map((myData) => {
  return {
    queryKey: ['myquerykey'],
    queryFn: myQueryFn
  }
}

return useQueries(buildQuery)

Now in my component, I have:

const myData: any = useMyList()

const allQueriesSuccess: boolean = myData.every((result: any) => result.isSuccess)

The response data from the queryFunction will match a type already setup named IMyData . How can I properly type myData and result? myData will be a react query standard response array with the data field for each element matching IMyData .

Adding a type to the data and error can be done a couple of ways and the loading states are boolean so there wouldn't be a need to provide a type, ie isLoading wouldn't need a type. Below I've made a call to an API to fetch some data and have provided types for each approach - comments are in the code.

You can read up more on how these work in greater detail from the docs at https://tanstack.com/query/v4/docs/react/typescript

import {
  useQuery,
  QueryClient,
  QueryClientProvider
} from "@tanstack/react-query";
import "./styles.css";
import axios from "axios";

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

const queryClient = new QueryClient();

function MyComponent() {
  const fetchTodo = (): Promise<Todo> =>
    axios
      .get("https://jsonplaceholder.typicode.com/todos/1")
      .then((response) => response.data);

  // data is inferred from fetch const, error is unknown
  const { data: inferredData, error: errorUnknown } = useQuery({ queryKey: ["todo"], queryFn: fetchTodo });
  
  // specify the error and data type as type param
  const { data: typedData, error: typedError } = useQuery<Todo, Error>({ queryKey: ["todo"], queryFn: fetchTodo });

  // runtime check errorUnknown is an error
  if (errorUnknown instanceof Error) {
    return <p>Woops!</p>
  }

  // trusting the type matches return value
  if (typedError) {
    return <p>{typedError.message}</p>
  }

  return (
    <div>
      <h1>useQuery</h1>
      <p>inferredData: {inferredData && inferredData.title}</p>
      <p>typedData: {typedData && typedData.title}</p>
    </div>
  );
}

export default function App() {
  return (
    <QueryClientProvider client={queryClient}>
      <MyComponent />
    </QueryClientProvider>
  );
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM