Showing data obtained from external sources is a fundamental
Here are the steps to start using React Query to enhance your code:
1.Understand the difference between client state and server state
Client state exists in the browser, such as form state, dark mode, or whether a modal is open or closed. Server state probably resides in a database and is served asynchronously.
Always use React Query for server state. For client state, use native hooks like useState or useReducer.
2. Install React-Query in your project
Follow the installation instructions and remember to set up the query client provider
3. Replace data fetching code and states in your code with the useQuery hook Instead of writing this:
const [data, setData] = useState(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState(null);
useEffect(() => {
async function fetchData() {
try {
const response = await fetch('https://rickandmortyapi.com/api/character');
if (!response.ok) {
throw new Error('Network response was not ok');
}
const result = await response.json();
setData(result.results);
} catch (err) {
setError(err);
} finally {
setLoading(false);
}
}
fetchData();
}, []);
write this:
function fetchRickAndMortyCharacters() {
return fetch('https://rickandmortyapi.com/api/character')
.then(response => {
if (!response.ok) {
throw new Error('Network response was not ok');
}
return response.json();
})
.then(data => data.results);
}
const { data, isLoading, isError, error } = useQuery(['rickAndMortyCharacters'], fetchRickAndMortyCharacters);
The data you need to render will be in the destructured data. Here is an example of how you can render the result:
if (isLoading) return <p>Loading...</p>;
if (isError) return <p>Error: {error.message}</p>;
if (!data) return <p>No data available</p>;
return (
<ul>
{data.map(character => (
<li key={character.id}>{character.name}</li>
))}
</ul>
);
4.Convert the useQuery hook into a custom hook
For better reusability, abstract this into a custom hook:
export function useRickAndMortyCharacters() {
return useQuery(['rickAndMortyCharacters'], fetchRickAndMortyCharacters);
}
now, from any component, you can just call the custom hook like so:
const { data, isLoading, isError, error } = useRickAndMortyCharacters();
That's it! If you want to go any further, read the docs and play around with different query options or with mutations.
Thanks for reading!
Top comments (0)
Some comments may only be visible to logged-in visitors. Sign in to view all comments.