When using the useQuery hook from React Query to fetch data, you can access various data and states by destructuring the returned object. Here's how to do it, along with some examples:
Using useQuery
First, ensure you have installed the react-query library and imported the useQuery hook into your component.
javascriptimport { useQuery } from 'react-query';
Setting Up the Request
You can initiate a request by passing a unique key and a function. This function is responsible for fetching data, typically an API request.
javascriptconst fetchPlanets = async () => { const response = await fetch('https://swapi.dev/api/planets/'); if (!response.ok) { throw new Error('Network response was not ok'); } return response.json(); }; const { data, error, isLoading, isError } = useQuery('planets', fetchPlanets);
Accessing Data and Handling States
By accessing the returned values from useQuery, you can access several important properties:
- data: The data returned successfully.
- error: The error message when the request fails.
- isLoading: True when the request is still loading.
- isError: True if an error occurred.
Example
Suppose you are developing an application that displays planet information. You can use the code snippet above as follows:
javascriptfunction Planets() { const { data, error, isLoading, isError } = useQuery('planets', fetchPlanets); if (isLoading) return <div>Loading...</div>; if (isError) return <div>Error: {error.message}</div>; return ( <div> <h2>Planets</h2> <ul> {data.results.map(planet => ( <li key={planet.name}>{planet.name}</li> ))} </ul> </div> ); }
In this example, when useQuery is fetching data, it displays a loading indicator. If an error occurs, it shows the error message. Once the request is successful, it renders a list containing the names of the planets.
Conclusion
Using the useQuery hook from React Query, you can easily initiate asynchronous requests and manage states in your React applications. By destructuring the returned object, you can access the data, states, and error information, allowing you to display these appropriately in your UI.