Intro
I have written two articles about useEffect for beginners ((Second Argument and Cleanup Function).
Today, as an exercise to help you understand more, we will create a simple loading page that switches to the main page after API data is fetched.
It will be a minimal implementation that does not include difficult codes, so it will be easy to understand.
How We Do
From this code, let's consider how it could be implemented.
import React, { useState, useEffect } from 'react';
// API we use
const API_URL = 'https://jsonplaceholder.typicode.com/posts/1';
export default function App() {
const [data, setData] = useState(null); // data state
const [loading, setLoading] = useState(true); // loading state
//
useEffect((), []);
return (
<div>
{loading ? (
{/* loading */}
<p>Loading...</p>
) : (
<div>
{/* display data */}
<p>Data: {data?.title}</p>
</div>
)}
</div>
);
}
You need to fetch data from the API and retrieve values with setData
. You also need to change the value of setLoading
according to the jsx conditional expression.
There are probably several ways to do, but I will try to implement this using then-catch method. My idea of useEffect code is like this.
useEffect(() => {
// Start here
fetch(API_URL)
.then(response => response.json())
.then(result => {
setData(result); // Set data
setLoading(false); // Loading is done, now it's false
})
.catch(error => {
console.error('Error fetching data:', error);
setLoading(false);
});
}, []);
First, the API is JSON, so respond in JSON.
As shown in the code, set the fetched data in setData
, and change the state of Loading from true to false, to switch the elements in conditional expression in jsx side.
By changing useEffect to this, the previous code should work fine!
Let's see completed code.
import React, { useState, useEffect } from 'react';
// API we use
const API_URL = 'https://jsonplaceholder.typicode.com/posts/1';
export default function App() {
const [data, setData] = useState(null); // data state
const [loading, setLoading] = useState(true); // loading state
//
useEffect(() => {
// Start here
fetch(API_URL)
.then(response => response.json())
.then(result => {
setData(result); // Set data
setLoading(false); // Loading is done, now it's false
})
.catch(error => {
console.error('Error fetching data:', error);
setLoading(false);
});
}, []);
return (
<div>
{loading ? (
{/* loading */}
<p>Loading...</p>
) : (
<div>
{/* display data */}
<p>Data: {data?.title}</p>
</div>
)}
</div>
);
}
Outro
I hope this article helps to you. Happy coding!