One of the most used thing in React โ๏ธ is API Request to a remote Server. Since APIs have become part and parcel of our daily life, they are involved in almost everything we do on the world wide web. An API request occurs when a developer adds an endpoint to a URL and makes a call to the server.
A basic API Request in React/JavaScript using axios
looks like this-
axios
.get("https://api.example.com/users/")
.then((res) => console.log(res.data))
.catch((err) => console.log(err));
In the above JavaScript (axios) syntax, the API Request has been made to https://api.example.com
Domain (also knows as BASE URL) and /users/
end-point.
Request to Local JSON File ๐
Making GET Request to a Local JSON File is really simple, but there are few prerequisites you need to make sure, they are followed.
Make sure, JSON File is accessible through the server, ie. the file should be in
public/
folder.
Create public/db/users.json
[
{
id: 1,
first_name: "John",
last_name: "Doe",
},
{
id: 2,
first_name: "Jane",
last_name: "Doe",
},
{
id: 3,
first_name: "Johny",
last_name: "Doe",
},
];
NOTE: Check if the JSON File is accessible at http://localhost:3000/db/users.json when the server is running.
This time, if you want to make GET request to the JSON File, do it like this-
axios
.get("/db/users.json")
.then((res) => console.log(res.data))
.catch((err) => console.log(err));
React Example
Create React App
$ npx create-react-app my-app
---> 100%
$ cd my-app
Install
axios
$ yarn add axios
Add JSON File
public/db/users.json
[
{
id: 1,
first_name: "John",
last_name: "Doe",
},
{
id: 2,
first_name: "Jane",
last_name: "Doe",
},
{
id: 3,
first_name: "Johny",
last_name: "Doe",
},
];
Update
App.js
import { useEffect, useState } from "react";
import axios from "axios";
function App() {
const [users, setUsers] = useState([]);
useEffect(() => {
axios
.get("/db/users.json")
.then((res) => setUsers(res.data))
.catch((err) => console.log(err));
}, []);
return (
<div>
<ul>
{users.map((user, index) => (
<li key={index}>
#{user.id}: {user.first_name} {user.last_name}
</li>
))}
</ul>
</div>
);
}
export default App;
Run the development server
$ yarn start
I hope, you guys liked this quick tutorial API Request โก to Local JSON File ๐ in React โ๏ธ
. If so, then please don't forget to drop a Like โค๏ธ
And also, help me reach 1k Subscribers ๐คฉ, on my YouTube channel.
Happy Coding! ๐๐ป
Top comments (1)
Thanks a bunch! This helped me learn how to fetch data from local JSON file in React component. Detailed and precise, can't ask for more!!