Fetching Data with Axios vs. useQuery Hook
Show how data fetching is done using Axios with async/await and compare it with the useQuery hook in React Query, including error handling and displaying loading states.
import axios from 'axios';
import React, { useState, useEffect } from 'react';
function FetchWithAxios() {
const [data, setData] = useState([]);
const [isLoading, setIsLoading] = useState(false);
const [error, setError] = useState(null);
useEffect(() => {
const fetchData = async () => {
setIsLoading(true);
try {
const response = await axios('https://jsonplaceholder.typicode.com/posts?_limit=5');
setData(response.data);
} catch (error) {
setError(error);
} finally {
setIsLoading(false);
}
};
fetchData();
}, []);
if (isLoading) return <div>Loading...</div>;
if (error) return <div>An error occurred: {error.message}</div>;
return (
<ul>{data.map(post => <li key={post.id}>{post.title}</li>)}</ul>
);
}
export default FetchWithAxios;
This code snippet demonstrates how to fetch data using Axios with async/await inside a React component. useState and useEffect hooks manage state and side effects. It handles loading states and errors gracefully.
import { useQuery } from 'react-query';
import axios from 'axios';
const fetchPosts = async () => {
const { data } = await axios('https://jsonplaceholder.typicode.com/posts?_limit=5');
return data;
};
function FetchWithReactQuery() {
const { isLoading, error, data } = useQuery('posts', fetchPosts);
if (isLoading) return <div>Loading...</div>;
if (error) return <div>An error occurred: {error.message}</div>;
return (
<ul>{data.map(post => <li key={post.id}>{post.title}</li>)}</ul>
);
}
export default FetchWithReactQuery;
This code example illustrates fetching data with the useQuery hook from React Query, encapsulating fetching, loading, and error state logic. It uses Axios for the HTTP request.