Designing a React Component
I'm focusing on the user's request to design a React functional component that fetches data from a public API, displays it in a table, and includes loading states. I think JSONPlaceholder or PokeAPI could work well. I'll implement useEffect and useState for data fetching and error handling, along with a loading message, maybe a CSS spinner. I should also consider best practices like using an abort controller for cleanup to avoid memory leaks. Overall, I'll ensure the component is functional and concise.Creating a Users Table Component
I'm considering using plain CSS for the component and need to provide a code snippet that includes importing React, useEffect, and useState. I think using the JSONPlaceholder API is a good choice for fetching user data. I’ll also implement error handling with a hasError state to show any messages if something goes wrong. My plan is to provide the full component code along with a CSS snippet, ensuring everything is straightforward and in one file. I'll ensure to use async functions and manage states like isLoading, error, and users.Coding the Component Logic
I’m getting into the coding details with useState for data, loading, and error management. I'll set up useEffect to fetch data but add an ignore flag to prevent memory leaks. Inside the fetch, I’ll handle responses, parsing JSON, and setting data or errors carefully.
In the JSX, if loading, I want to show a spinner; if there's an error, show the error message; otherwise, display the user data in a table. I plan to define a basic spinner with some CSS and suggest adding those styles to the appropriate stylesheet.Defining the Spinner CSS
I'm planning to provide the CSS for the spinner, which I'd include in a stylesheet like index.css. The spinner will be 40px wide and high, with a light border and a blue top border to create that spinning effect. I'll also set up the keyframes for smooth animation. Once everything is defined, I'll ensure the component returns the right container that includes this spinner for use when loading data. Let's finalize the response! Here’s a complete example of a React functional component that:
- Fetches data from a public API (
jsonplaceholder.typicode.com/users)
- Shows a loading spinner while fetching
- Handles and displays errors
- Renders the data in a table
Component (UsersTable.jsx)
import React, { useEffect, useState } from "react";
const UsersTable = () => {
const [users, setUsers] = useState([]);
const [isLoading, setIsLoading] = useState(true);
const [error, setError] = useState(null);
useEffect(() => {
const controller = new AbortController();
const fetchUsers = async () => {
try {
setIsLoading(true);
setError(null);
const response = await fetch(
"https://jsonplaceholder.typicode.com/users",
{ signal: controller.signal }
);
if (!response.ok) {
throw new Error(`Request failed with status ${response.status}`);
}
const data = await response.json();
setUsers(data);
} catch (err) {
if (err.name !== "AbortError") {
setError(err.message || "Something went wrong");
}
} finally {
setIsLoading(false);
}
};
fetchUsers();
return () => controller.abort();
}, []);
if (isLoading) {
return (
<div style={styles.center}>
<div className="spinner" />
<span style={{ marginTop: 8 }}>Loading users...</span>
</div>
);
}
if (error) {
return (
<div style={styles.center}>
<p style={{ color: "red" }}>Error: {error}</p>
</div>
);
}
return (
<div style={{ padding: "1rem" }}>
<h2>Users</h2>
<table style={styles.table}>
<thead>
<tr>
<th style={styles.th}>Name</th>
<th style={styles.th}>Username</th>
<th style={styles.th}>Email</th>
<th style={styles.th}>City</th>
<th style={styles.th}>Company</th>
</tr>
</thead>
<tbody>
{users.map((user) => (
<tr key={user.id}>
<td style={styles.td}>{user.name}</td>
<td style={styles.td}>{user.username}</td>
<td style={styles.td}>{user.email}</td>
<td style={styles.td}>{user.address.city}</td>
<td style={styles.td}>{user.company.name}</td>
</tr>
))}
</tbody>
</table>
</div>
);
};
// Simple inline styles for the example
const styles = {
center: {
display: "flex",
flexDirection: "column",
alignItems: "center",
marginTop: "2rem",
},
table: {
width: "100%",
borderCollapse: "collapse",
marginTop: "1rem",
},
th: {
borderBottom: "2px solid #ccc",
textAlign: "left",
padding: "8px",
backgroundColor: "#f5f5f5",
},
td: {
borderBottom: "1px solid #eee",
padding: "8px",
},
};
export default UsersTable;
Spinner CSS
Add this to your global CSS file (e.g., index.css or App.css):
.spinner {
width: 40px;
height: 40px;
border: 4px solid #ddd;
border-top-color: #3498db;
border-radius: 50%;
animation: spin 0.8s linear infinite;
}
@keyframes spin {
to {
transform: rotate(360deg);
}
}
Usage
In your main app component:
import React from "react";
import UsersTable from "./UsersTable";
const App = () => {
return (
<div>
<UsersTable />
</div>
);
};
export default App;
This covers fetching, loading spinner, error handling, and rendering the results in a table using a functional component with hooks.