0% found this document useful (0 votes)
60 views2 pages

React Fetch Users with useEffect

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
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
60 views2 pages

React Fetch Users with useEffect

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
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd

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