0% found this document useful (0 votes)
5 views

3 UseEffect Example 1

The document is a React functional component that fetches user data from an API and displays it. It manages loading states and error handling using React hooks. The component renders a loading message, an error message, or a list of users with their names and emails based on the fetch operation's outcome.

Uploaded by

KundiLokesh
Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

3 UseEffect Example 1

The document is a React functional component that fetches user data from an API and displays it. It manages loading states and error handling using React hooks. The component renders a loading message, an error message, or a list of users with their names and emails based on the fetch operation's outcome.

Uploaded by

KundiLokesh
Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 2

import React, { useState, useEffect } from "react";

const URL = "https://jsonplaceholder.typicode.com/users";

const Final = () => {


const [usersData, setUsersData] = useState([]);
const [loading, setLoading] = useState(false);
const [isError, setIsError] = useState({ status: false, msg: "" });

const fetchUsersData = async (apiURL) => {


setLoading(true);
setIsError({ status: false, msg: "" });
try {
const response = await fetch(apiURL);
const data = await response.json();
setUsersData(data);
setLoading(false);
setIsError({ status: false, msg: "" });
if (response.status === 404) {
throw new Error("data not found");
}
} catch (error) {
setLoading(false);
setIsError({
status: true,
msg: error.message || "something went wrong, pls try again!",
});
}
};

useEffect(() => {
fetchUsersData(URL);
}, []);

if (loading) {
return (
<div>
<h3>Loading...</h3>
</div>
);
}

if (isError?.status) {
return (
<div>
<h3 style={{ color: "red" }}>{isError?.msg}</h3>
</div>
);
}

return (
<div>
<h1>useEffect example - 1</h1>
<ul>
{usersData.map((eachUser) => {
const { id, name, email } = eachUser;
return (
<li key={id}>
<div>{name}</div>
<div>{email}</div>
</li>
);
})}
</ul>
</div>
);
};

export default Final;

You might also like