How To Fetch API Call Using JSON Server In ReactJS (2024)

Introduction

In this article, we will learn how to Fetch API calls using the JSONserver in React applications.

Now we will start by creating a new project.

Step 1

Create a React project setup using the below commands or however, you create your React app.

npx create-react-app projectname

Example,

npx create-react-app sample-fetch

Step 2 -Installing React JSON-server

Since JSON Server is available as an NPM package, we can perform the installation by using the Node.js package manager.

Run the below command in the terminal.

npm install Json-server

How To Fetch API Call Using JSON Server In ReactJS (1)

Step 3 -Create a sample JSON file with data

JSON Server will take a JSON file from your main project folder and turn it into a RESTful database with all the right routes.

I have created a JSON file db.json inside my newly created project with the following sample data.

{ "posts": [{ "id": 1, "name": "Satheesh", "email": "[emailprotected]", "adderss": "South street" }, { "id": 2, "name": "John", "email": "[emailprotected]", "adderss": "North street" }, { "id": 3, "name": "Robert", "email": "[emailprotected]", "adderss": "East street" }, { "id": 4, "name": "Mani", "email": "[emailprotected]", "adderss": "West street" }], "comments": [{ "id": 1, "body": "some comment", "postId": 1 }], "profile": { "name": "typicode" }}

Step 4 -Running the server

Start JSON server by executing the following command.

json-server –watch db.json

How To Fetch API Call Using JSON Server In ReactJS (2)

our JSON Server will be running on port3000.

Step 5 -Fetch API

  • It is available in modern browsers and allows us to make requests using JavaScript promises.
  • We can use the fetch() method to get the data.
  • To make a simple GET request with fetch, it includes the URL endpoint to which we want to make our request
  • UsesFetchAPI toGETthe list of all Posts. ( endpoint http://localhost:3000/postsand others are provided by the already running JSON Server)
  • Thestateof theAppcomponent (App.js) and populates theusers state variable
    getFetchUsers() { this.setState({ loading: true }, () => { fetch("http://localhost:3000/posts").then(res => res.json()).then(result => this.setState({ loading: false, users: result })).catch(console.log); });}

In Fetch API Call,

First is Returning JSON object

The second is Printing the value.

Step 6

Src/App.js

import React, { Component} from 'react';class App extends React.Component { state = { isLoading: true, users: [], error: null }; getFetchUsers() { this.setState({ loading: true }, () => { fetch("http://localhost:3000/posts").then(res => res.json()).then(result => this.setState({ loading: false, users: result })).catch(console.log); }); } componentDidMount() { this.getFetchUsers(); } render() { const { users, error } = this.state; return ( <React.Fragment> <h1>All User</h1> { error ? <p> { error.message } < /p> : null} { users.map(user => { const { adderss, name, email } = user; return ( <div key={name}> <p>Name: {name}</p> <p>Email: {email}</p> <p>Address: {adderss}</p> <hr /> </div> ); }) } < /React.Fragment> ); } }export default App;

Step 7

Now we will run the application.

How To Fetch API Call Using JSON Server In ReactJS (3)

npm run start

On successful execution of the above command, it will show the browser,

How To Fetch API Call Using JSON Server In ReactJS (4)

How To Fetch API Call Using JSON Server In ReactJS (2024)

FAQs

How do I fetch data from JSON API in React? ›

Different Ways to Fetch Data in React
  1. Use the stale-while-revalidate (SWR) method. This method is used to fetch data from a server and is used in React. ...
  2. Use the JavaScript Fetch() method. ...
  3. Use the React Query library. ...
  4. Use the Axios Library. ...
  5. Use the useFetch custom hook from react-fetch-hook.
Dec 14, 2023

How to fetch data from JSON server? ›

Making a GET Request to Fetch Data

Once the JSON Server runs, you can start making HTTP requests to interact with your data. To fetch data from the server, you make a GET request. For instance, you would send a GET request to http://localhost:3000/users to fetch all users.

How to fetch JSON data using Fetch API? ›

To fetch post JSON data using API, you need to follow these steps: fetch('https://example.com/api/data', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON. stringify({ key1: 'value1', key2: 'value2' }) }) .

How to extract data from JSON API? ›

Examples: Extracting properties

To extract the name and projects properties from the JSON string, use the json_extract function as in the following example. The json_extract function takes the column containing the JSON string, and searches it using a JSONPath -like expression with the dot . notation.

How to access JSON data from response? ›

Getting a specific property from a JSON response object
  1. response. wind. speed.
  2. console. log("wind speed: " + response. wind. speed);
  3. $. ajax(settings). done(function (response) { console. log(response); console. ...
  4. var content = response. wind. speed;
  5. <div id="windSpeed">Wind speed: </div>
  6. $("#windSpeed"). append(content);

How do you call JSON data in ReactJS? ›

To pass JSON values into a React component, you can use props. Props are a way of passing data from a parent component to its child components. You can pass the JSON values as props when rendering the component. You can access the props in the component's function or class and use them to display the desired data.

How to fetch data from a JSON file in js? ›

Follow these steps to read the JSON file using the fetch API method:
  1. Create a JSON file and add data to it.
  2. Open the JavaScript file.
  3. In the fetch method pass the path of the JSON file.
  4. Use the . json() method to parse the data in JSON format.
  5. Display the content in the console.
Feb 23, 2024

How to fetch the data from a JSON object? ›

getJsonObject() Method

It is used to get the (JsonObject)get(name). The method parses an argument name of type String whose related value is to be returned. It returns the object of the associated mapping for the parse's parameter.

How do I fetch POST API data? ›

To make a POST request, you need to add the configuration object to the fetch() method. This object should include the HTTP method (in this case, POST) and any data you want to send in the body of the request. This code will collect data from an HTML form and submit it via a POST request.

What is JSON () in fetch? ›

fetch-json is a lightweight JavaScript library to reduce the boilerplate code needed to make HTTP calls to JSON endpoints. fetch-json automatically: Adds the HTTP header Content-Type: application/json to ensure the correct data type.

How to fetch data from API in React using functional component? ›

Let's get started!
  1. Set Up a New React. js Project. ...
  2. Create a Component for Fetching Data. React. ...
  3. Perform the API Request. In this step, we create the fetchData function to make an API request using the fetch function. ...
  4. Handle the API Response. ...
  5. Display the Data in the Component. ...
  6. Handle Loading and Error States.
Aug 2, 2023

What are different ways to call API in React JS? ›

There are three common ways to make API calls in React:
  1. XMLHttpRequest.
  2. Fetch API.
  3. Axios.
Sep 5, 2023

Is Axios better than Fetch? ›

Axios returns the data in the response object, which is more convenient for accessing the data directly. Fetch only rejects the promise if there is a network error, not if the response has an error status. Axios handles errors in the catch block, which makes it easier to deal with error responses.

How do I fetch data from API in react admin? ›

Whenever react-admin needs to communicate with your APIs, it does it through an object called the dataProvider . The dataProvider exposes a predefined interface that allows react-admin to query any API in a normalized way. For instance, to query the API for a single record, react-admin calls dataProvider.

How to get data from a JSON file using axios? ›

To send a GET request with Axios and JSON data, use the axios. get() method and pass in the URL of the API endpoint from where you want to retrieve data.

Why axios instead of fetch? ›

Axios automatically transforms the data to and from JSON, while fetch() requires you to call response. json() to parse the data to a JavaScript object. Axios provides the data in the response object, while fetch() provides the response object itself, which contains other information such as status, headers, and url.

How to grab JSON from URL? ›

To read a JSON response there is a widely used library called urllib in python. This library helps to open the URL and read the JSON response from the web. To use this library in python and fetch JSON response we have to import the json and urllib in our code, The json. loads() method returns JSON object.

Top Articles
Latest Posts
Article information

Author: Nathanial Hackett

Last Updated:

Views: 5996

Rating: 4.1 / 5 (72 voted)

Reviews: 95% of readers found this page helpful

Author information

Name: Nathanial Hackett

Birthday: 1997-10-09

Address: Apt. 935 264 Abshire Canyon, South Nerissachester, NM 01800

Phone: +9752624861224

Job: Forward Technology Assistant

Hobby: Listening to music, Shopping, Vacation, Baton twirling, Flower arranging, Blacksmithing, Do it yourself

Introduction: My name is Nathanial Hackett, I am a lovely, curious, smiling, lively, thoughtful, courageous, lively person who loves writing and wants to share my knowledge and understanding with you.