RomeoHY
RomeoHY

Reputation: 59

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

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?

Upvotes: 2

Views: 3356

Answers (2)

Tomas Vancoillie
Tomas Vancoillie

Reputation: 3878

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();

Upvotes: 3

RomeoHY
RomeoHY

Reputation: 59

I try 2 answer..

  1. using query array...

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

  2. type select

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

Upvotes: 0

Related Questions