Client-side Data Fetching with useEffect Hook
Showcase how to fetch data on the client side in a functional component using React's useEffect hook in combination with the useState hook.
import React, { useState, useEffect } from 'react';
function DataFetchingComponent() {
// State to store the fetched data
const [data, setData] = useState(null);
// State to store loading status
const [isLoading, setIsLoading] = useState(false);
// State to store any errors
const [error, setError] = useState(null);
useEffect(() => {
// Function to fetch data
const fetchData = async () => {
setIsLoading(true);
try {
const response = await fetch('https://api.example.com/data');
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const result = await response.json();
setData(result);
} catch (e) {
setError(e.message);
} finally {
setIsLoading(false);
}
};
// Call the fetchData function
fetchData();
}, []); // The empty array means this effect runs once after the initial render
// Render logic based on state
if (error) {
return <div>Error: {error}</div>;
}
if (isLoading) {
return <div>Loading...</div>;
}
if (data) {
return <div>{JSON.stringify(data)}</div>;
}
return <div>No data fetched</div>;
}
export default DataFetchingComponent;
This code defines a React functional component that uses the useState and useEffect hooks to perform client-side data fetching. It declares the state variables to store the data, loading status, and any potential errors. The useEffect hook runs once after the initial render to fetch data from an API endpoint, and the rendering logic handles different states of the fetch operation, displaying the data, loading indicator, or an error message accordingly.