React Query is a data fetching library for React that makes data fetching, caching, and synchronizing easier. Now let's take a look at how we can fetch data using React Query.
Providing query client:
The first and foremost method of using React Query is to provide a query client to your application.
As we see above, we are importing QueryClientProvider and QueryClient from React Query. We are using QueryClient to handle the global data caching. The QueryClientProvider component can be used to provide a QueryClient to our application.
Creating query functions:
Query functions are those that are used to fetch data from the server.
As we see above, getPosts is a query function that fetches all the posts. In our case, we are using Axios to fetch the data.
Using the useQuery hook to fetch data from the network and cache it:
As we see above, we are importing useQuery from React Query. The useQuery hook accepts two parameters. The first one is key; in our case, it is "posts." Keys are generally used to uniquely identify a particular HTTP request. The second parameter for useQuery is a query function, which in our case is "getPosts". Query functions are used to fetch data from the server. useQuery always returns some of the most useful properties which are as listed below.
- data
- dataUpdatedAt
- error
- errorUpdatedAt
- failureCount
- isError
- isFetched
- isFetchedAfterMount
- isFetching
- isIdle
- isLoading
- isLoadingError
- isPlaceholderData
- isPreviousData
- isRefetchError
- isRefetching
- isStale
- isSuccess
- refetch
- remove
- status
In our case we are using only isLoading, isError and data properties.The data that is fetched from the server is always stored in the data property returned by the useQuery hook. isLoading is a boolean property value that is set to true when data fetching is in progress. isError is also a boolean property value that is set to true when there is an error while fetching data from the server.
Top comments (0)