React with json-server

Agenda

  1. Create react app
  2. Install json-server
  3. Create database file
  4. Add npm scripts
  5. Call the api from component via useEffect
  6. Run

1. Create react app


1
npx create-react-app react-with-json-server


1. Install json-server


1
npm i json-server


3. Create database file

1
mkdir data & touch data/db.json
1
2
3
4
5
6
7
8
9
10
11
12
13
// data/db.json
{
"users": [
{
"id": "1",
"name": "Ichi"
},
{
"id": "2",
"name": "Ni"
}
]
}

4. Add npm scripts


1
2
"server": "json-server --watch data/db.json --port 8000",
"dev": "npm run start & npm run server"

5. Call the api from component via useEffect


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
import { useEffect, useState } from "react";

const App = () => {
const [users, setUsers] = useState(null);

useEffect(() => {
const url = "http://localhost:8000/users";

const fetchData = async () => {
const response = await fetch(url);
const json = await response.json();
setUsers(json);
};

fetchData();
}, []);

return (
<div>
<p>{JSON.stringify(users)}</p>
</div>
);
};

export default App;

6. Run


1
npm run development

🔥 🔥 🔥 🔥 🔥 🔥 🔥 🔥 🔥 🔥

Result - localhost:3000

Result - localhost:8000/users