how to get data from react-query(V4) Promise

Viewed 186

I trying react-query for data-fetching (in Typescipt)

in my books, maybe I guess use react-query V3. but I want to react-query v4

in my books, using react-query...

const useLatestMovie = () => {    
return useQuery<AxiosResponse<MovieDetail>, AxiosError>('latestMovie', latestApi)
}

and call function other files,

const { isLoading, data } = useLatestMovie()

but this code isLiading, data not exist because "Property 'data' does not exist on type 'Promise'."

how do I make this code can work?

2 Answers

You can type your query functions by just specifying the type with the http request.

In the example below we typed the get request with an array of Users. Because the data is typed and returned in the useQuery hook, typescript will implicitly know the type.

async function fetchUsers() {
  const { data } = await http.get<User[]>('/users');

  return data;
}

export function useUsers() {
  return useQuery(['users'], () => fetchUsers());
}

When we use the useUsers hook in our application, the users variable will be of type Users[]

const { data: users } = useUsers();

I try 2 answer..

  1. using query array...

    return useQuery<AxiosResponse, AxiosError>(['latestMovie'], latestApi)

  2. type select

    return useQuery<MovieDetail, Error>(['latestMovie'], latestApi)

Related