ReactJS: Practice Set 5

Rahul Kumar
8 min readMar 11, 2024

This set is about practicing useEffect and useState hook in React.

Q1. Create a React component where all the users are fetched using fake fetch and listed on the DOM. Show the online users in green color and the offline users in red color.

fakeFetch has been provided:

fakeFetch1.jsx

export const fakeFetch = (url) => {
return new Promise((resolve, reject) => {
setTimeout(() => {
if (url === "https://example.com/api/users/status") {
resolve({
status: 200,
message: "Success",
data: {
users: [
{ name: "Raju", status: "Online" },
{ name: "Pankaj", status: "Offline" },
{ name: "Sakshi", status: "Offline" },
{ name: "Kishore", status: "Offline" },
],
},
});
} else {
reject({
status: 404,
message: "No users Found",
});
}
}, 2000);
});
};

Output:

Solution:

OnlineOrOffline.jsx

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

import { fakeFetch } from "../api/fakeFetch1";

const OnlineOrOffline = () => {
const [usersData, SetUsersData] = useState([]);

const fetchData = async () => {
try {
const res = await fakeFetch("https://example.com/api/users/status");
const { status, users } = res.data;
SetUsersData(users);

if (status === 200) {
SetUsersData(users);
// console.log(users)
}
} catch (e) {
console.log(e);
}
};

useEffect(() => {
fetchData();
}, []);
return (
<div>
<h1>Online Users</h1>
<ul>
{usersData.map(({ name, status }, index) => {
return (
<li
key={index}
style={{
color: status === "Online" ? "green" : "red",
fontSize: "22px",
}}
>
{name} - {status}
</li>
);
})}
</ul>
</div>
);
};

export default OnlineOrOffline;

App.jsx

import "./App.css";

import OnlineOrOffline from "./practiceset5/OnlineOrOffline";

function App() {
return <OnlineOrOffline />;
}
export default App;

Q 2. Create a React component that fetches products data from an API endpoint using useEffect hook and display products (name, price, quantity) as a list on the screen using the useState hook.

  • A) Add a button, on click of which it displays only the items with more than 20 as quantity.

fakeFetch has been provided:

fakeFetch2.jsx

export const fakeFetch = (url) => {
return new Promise((resolve, reject) => {
setTimeout(() => {
if (url === "https://example.com/api/products") {
resolve({
status: 200,
message: "Success",
data: {
products: [
{ name: "Color Pencils", price: 50, quantity: 40 },
{ name: "Sketchpens", price: 110, quantity: 20 },
{ name: "Erasor", price: 20, quantity: 20 },
{ name: "Sharpner", price: 22, quantity: 30 },
],
},
});
} else {
reject({
status: 404,
message: "Items list not found.",
});
}
}, 2000);
});
};

On rendering:

On clicking on Button:

Solution:

ProductsCard.jsx

import React, { useEffect, useState } from "react";
import { fakeFetch } from "../api/fakeFetch2";

const ProductsCard = () => {
const [productData, setProductData] = useState([]);
const [error, setError] = useState();
const fetchData = async () => {
try {
const res = await fakeFetch("https://example.com/api/products");
const { products } = res.data;

setProductData(products);
} catch (e) {
setError(e);
}
};
useEffect(() => {
fetchData();
}, []);

return (
<div>
<h1>Products</h1>
<button
onClick={() =>
setProductData(productData.filter(({ quantity }) => quantity > 20))
}
>
Show products with qunatity more than 20
</button>
<ul>
{productData.map(({ name, price, quantity }, index) => {
return (
<li key={index}>
{name} - Rs. {price} - Quantity: {quantity}
</li>
);
})}
</ul>
</div>
);
};

export default ProductsCard;

App.jsx

import "./App.css";

import ProductsCard from "./practiceset5/ProductsCard";

function App() {
return <ProductsCard />
}
export default App;

Q 3. In the above question after you have listed all the items, add a button which says “Filter by Price”. On click of the button, display only the items with price less than 100.

Solution:

Component.jsx

import React, { useEffect, useState } from "react";
import { fakeFetch } from "../api/fakeFetch2";

const ProductsCard = () => {
const [productData, setProductData] = useState([]);
const [error, setError] = useState();
const fetchData = async () => {
try {
const res = await fakeFetch("https://example.com/api/products");
const { products } = res.data;

setProductData(products);
} catch (e) {
setError(e);
}
};
useEffect(() => {
fetchData();
}, []);

return (
<div>
<h1>Products</h1>
<button onClick={() =>
setProductData(productData.filter(({ price }) => price < 100))
}>Filter by Price</button>
<ul>
{productData.map(({ name, price, quantity }, index) => {
return (
<li key={index}>
{name} - Rs. {price} - Quantity: {quantity}
</li>
);
})}
</ul>
</div>
);
};

export default ProductsCard;

App.jsx

import "./App.css";

import ProductsCard from "./practiceset5/ProductsCard";

function App() {
return <ProductsCard />
}
export default App;

Q 4. Create a React component that fetches a user’s data from an API endpoint using useEffect hook and displays the data (name, image, likes, comments) on the screen using the useState hook.

Pass heading (”User Profile”) and width and height for image as props to the component.

fakeFetch has been provided:

fakeFetch3.jsx

export const fakeFetch = (url) => {
return new Promise((resolve, reject) => {
setTimeout(() => {
if (url === "https://example.com/api/user") {
resolve({
status: 200,
message: "Success",
data: {
name: "Saroj",
image:
"https://cdn.pixabay.com/photo/2016/07/11/15/43/woman-1509956_1280.jpg",
likes: 500,
comments: 10,
},
});
} else {
reject({
status: 404,
message: "user data not found.",
});
}
}, 2000);
});
};

Solution:

UserData.jsx

import React, { useEffect, useState } from "react";
import { fakeFetch } from "../api/fakeFetch3";

const UserCard = ({ height, width }) => {
const [userData, setUserData] = useState();
const [error, setError] = useState();

const fetchData = async () => {
try {
const res = await fakeFetch("https://example.com/api/user");
const { status, data } = res;

if (status === 200) {
setUserData(data);
}
} catch (e) {
setError(e);
}
};

useEffect(() => {
fetchData();
}, []);

return (
<div>
<h1>User Profile</h1>
{userData ? (
<div>
<img src={userData?.image} alt="" height={height} width={width} />
<p>Name: {userData?.name}</p>
<p>Comments: {userData?.comments}</p>
<p>Likes: {userData?.likes}</p>
</div>
) : (
<div>Fetching data...</div>
)}
</div>
);
};

export default UserCard;

App.jsx

import "./App.css";

import UserCard from "./practiceset5/UserCard";

function App() {
return <UserCard height={"200px"} width={"200px"}/>
}
export default App;

Q5. Create a React component that fetches users data from an API endpoint using useEffect hook and display users data (name, image, likes, comments) as a list on the screen using the useState hook.

a. Show “Loading…” until your data displays on the DOM.

b. Handle errors by showing an error message on the DOM, in case of any error.

fakeFetch has been provided:

export const fakeFetch = (url) => {
return new Promise((resolve, reject) => {
setTimeout(() => {
if (url === "https://example.com/api/users") {
resolve({
status: 200,
message: "Success",
data: [
{
name: "Saroj",
image:
"https://cdn.pixabay.com/photo/2017/06/13/13/06/girl-2398822_1280.jpg",
likes: 500,
comments: 10,
},
{
name: "Meeta",
image:
"https://cdn.pixabay.com/photo/2017/06/13/13/06/girl-2398822_1280.jpg",
likes: 200,
comments: 1,
},
{
name: "Alia",
image:
"https://cdn.pixabay.com/photo/2017/06/13/13/06/girl-2398822_1280.jpg",
likes: 100,
comments: 5,
},
],
});
} else {
reject({
status: 404,
message: "users data not found.",
});
}
}, 2000);
});
};

Output:

Solution:

UsersCard.jsx

import React, { useEffect, useState } from "react";
import { fakeFetch } from "../api/fakeFetch4";

const UsersCard = ({ height, width }) => {
const [userData, setUserData] = useState();
const [error, setError] = useState(false);

const fetchData = async () => {
try {
const res = await fakeFetch("https://example.com/api/users");
const { status, data } = res;

if (status === 200) {
setUserData(data);
}
} catch (e) {
setError(true);
comsole.log(e);
}
};

useEffect(() => {
fetchData();
}, []);

return (
<div>
<h1>User Feed</h1>
{userData && !error ? (
userData.map(({ image, name, comments, likes }) => {
return (
<div>
<img src={image} alt="" height={height} width={width} />
<p>Name: {name}</p>
<p>Comments: {comments}</p>
<p>Likes: {likes}</p>
</div>
);
})
) : (
<div>Loading...</div>
)}
</div>
);
};

export default UsersCard;

App.jsx

import "./App.css";

import UsersCard from "./practiceset5/UsersCard";



function App() {
return <UsersCard height={"200px"} width={"200px"} />;
}
export default App;

Q 6. Create a React component that fetches chat data from an API endpoint using useEffect hook and display chat data (name and chat message) as a list on the screen using the useState hook.

a. Show “Loading Chats…” until your data displays on the DOM.

fakeFetch has been provided:

fakeFetch5.jsx

export const fakeFetch = (url) => {
return new Promise((resolve, reject) => {
setTimeout(() => {
if (url === "https://example.com/api/userchat") {
resolve({
status: 200,
message: "Success",
data: [
{
name: "Alia",
messages: [
{
from: "Alia",
message: "Good Morning",
},
{
from: "Ranvir",
message: "Good Morning, How are you?",
},
],
},
{
name: "Jeena",
messages: [
{
from: "Jeena",
message: "When is the meeting scheduled?",
},
{
from: "Seema",
message: "It is at 10AM tomorrow.",
},
],
},
{
name: "Abhay",
messages: [
{
from: "Abhay",
message: "Have you found a house yet?",
},
{
from: "John",
message: "No luck yet, still searching.",
},
{
from: "Abhay",
message:
"Hey, an apartment just got vacant in my bulding. Do you wanna have",
},
],
},
],
});
} else {
reject({
status: 404,
message: "users chat not found.",
});
}
}, 2000);
});
};

Output:

Solution:

Component.jsx

import React, { useEffect, useState } from "react";
import { fakeFetch } from "../api/fakeFetch5";

const UserChats = () => {
const [chats, setChats] = useState();

const fetchData = async () => {
const res = await fakeFetch("https://example.com/api/userchat");
// console.log(res.data)
setChats(res.data);
};

useEffect(() => {
fetchData();
}, []);

console.log(chats);
return chats ? (
<div>
{chats.map((chat) => {
return (
<ul>
<li style={{fontSize: "22px", fontWeight:"bold"}}>{chat.name}'s Chat:</li>
<ul>
{chat.messages.map((mes) => {
return (
<li>
<b> {mes.from} </b> : {mes.message}
</li>
);
})}
</ul>
</ul>
);
})}
</div>
) : (
<div style={{fontSize: "15px", fontWeight:"bold"}}> Chat Loading...</div>
);
};

export default UserChats;

App.jsx

import "./App.css";

import UserChats from "./practiceset5/UserChats";

function App() {
return <UserChats />;
}
export default App;

Q7. Create a React component called Comments.

a. Fetch the comments using thefake fetch and list the data on DOM.

b. Each comment component will have the text, user’s name and a delete button.

c. On click of the delete button, that particular comment object should be deleted and should not be visible on the DOM.

FakeFetch has been provided:

export const fakeFetch = (url) => {
return new Promise((resolve, reject) => {
setTimeout(() => {
if (url === "https://example.com/api/comments") {
resolve({
status: 200,
message: "Success",
data: {
comments: [
{
name: "Raju",
text: "Hello how are you long time no see!!!",
},
{ name: "Pankaj", text: "Party when??" },
{ name: "Sakshi", text: "Where are you currently staying" },
{ name: "Kishore", text: "Hello Buddy!!" },
],
},
});
} else {
reject({
status: 404,
message: "No comments Found",
});
}
}, 2000);
});
};

Output:

Solution:

Component.jsx

import React, { useEffect, useState } from 'react'
import { fakeFetch } from '../api/fakeFetch6';

const Comments = () => {
const[commentsData, setCommentsData] = useState();

const fetchData = async () => {
const res = await fakeFetch("https://example.com/api/comments");
console.log(res)
const {status, data} = res;
if(status === 200){
setCommentsData(data.comments)
}
}

const handleDelete = (index) => {
setCommentsData((prevComments) =>
prevComments.filter((i) => i !== index)
);
};


useEffect(()=>{
fetchData();
},[])


return (
<div>
<h1>Comments</h1>
{commentsData?.map(({ name, text }, index) => (
<div key={index}> {/* Add a unique key for each comment */}
<h2>{name}</h2>
<p>{text}</p>
<button onClick={() => handleDelete(index)}>delete</button>
</div>
))}
</div>
);
}

export default Comments;

App.jsx

import "./App.css";
import Comments from "./practiceset5/Comments";

function App() {
return <Comments />
}
export default App;

Thanks…

--

--