Hooks are a new addition in React 16.8 that allows you use state and other React features without writing a class.
When I am building my portfolio website I need to have many Get API calls so I create a custom hook named useFetch to fetch data from the WordPress REST API.
Create a new file named useFetch.js in the src/hooks directory with the following content:
import { useState, useEffect } from 'react';
const useFetch = (url) => {
const [data, setData] = useState(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState(null);
useEffect(() => {
const fetchData = async () => {
setLoading(true);
try {
const response = await fetch(url);
if (!response.ok) {
throw new Error('Network response was not ok');
}
const result = await response.json();
setData(result);
setLoading(false);
} catch (error) {
setError(error);
setLoading(false);
}
};
fetchData();
}, [url]);
return { data, loading, error };
};
export default useFetch;
Using the Custom Hook in a React Component
Now that we have our custom hook, we can use it in a React component to fetch and display data from the WordPress REST API. Let’s create a component named Posts.js in the src directory:
import React from 'react';
import useFetch from './useFetch';
const Posts = () => {
const { data, loading, error } = useFetch('https://your-wordpress-site.com/wp-json/wp/v2/posts');
if (loading) {
return <div>Loading...</div>;
}
if (error) {
return <div>Error: {error.message}</div>;
}
return (
<div>
<h1>Posts</h1>
<ul>
{data.map((post) => (
<li key={post.id}>
<h2>{post.title.rendered}</h2>
<div dangerouslySetInnerHTML={{ __html: post.excerpt.rendered }} />
</li>
))}
</ul>
</div>
);
};
export default Posts;
Handling Loading states and Errors
In the Posts component, we handle loading states and errors by conditionally rendering different content based on the loading and error states returned by our useFetch hook. This provides a better user experience by informing the user about the current state of data fetching.
Here’s a summary of what happens in the Posts component:
- If the data is still being loaded (
loadingistrue), we display a loading message. - If there was an error during the fetch operation (
erroris notnull), we display an error message. - If the data has been successfully fetched (
loadingisfalseanderrorisnull), we display the list of posts.