To fetch data from a JSON server in a React.js application, follow these steps:
JSON Server library ::
1️⃣ Set Up JSON Server
If you haven't already set up a JSON server, install it globally:
npm install -g json-server
Create a db.json
file with sample data ::
{
"users": [
{ "id": 1, "name": "John Doe", "email": "john@example.com" },
{ "id": 2, "name": "Jane Doe", "email": "jane@example.com" },
{ "id": 1, "name": "John Doe", "email": "john@example.com" },
{ "id": 2, "name": "Jane Doe", "email": "jane@example.com" },
]
}
Start the JSON server :
json-server --watch db.json --port 5000
Now your fake API is running at http://localhost:5000/users
.
2️⃣ Fetch Data in React
Inside your React component (e.g., App.js )
import React, { useEffect, useState } from "react";
const App = () => {
const [users, setUsers] = useState([]);
useEffect(() => {
fetch("http://localhost:5000/users")
.then((response) => response.json())
.then((data) => setUsers(data))
.catch((error) => console.error("Error fetching data:", error));
}, []);
return (
<div>
<h2>Users List</h2>
<ul>
{users.map((user) => (
<li>
{user.name} - {user.email}
</li>
))}
</ul>
</div>
);
};
export default App;