Fetch URL/API data in Reactjs in a simple way

React is not a framework , it’s a javascript library developed by facebook.



Before start the Project , First and forthwith I want to say if you have not already installed react then first you have to install it. For this you need to first download and install node and follow the commands.

 

To Install react-app Node Package :

            npm install -g create-react-app

Create your react app

      npx create-react-app app-name

This will create a sample ready to edit app that we need to edit and use. After this command you will see your app folder is got created, inside this there will be many folders but you have to focus on only two folders such as public and source folder.

So this all about installation of ReactJS and creating first app.

Now we will start with how to fetch and show url data in our first react app.

Fetch URL

In App.js file of src folder, Create Class Component, to define a React Component class , you need to extend React.Component :

  class App extends React.Component {
  constructor() {
    super();
    this.state = {
      items: [],
        }
      }  
    }

Constructor used to initialize object’s state in the class . it automatically gets called when object of class is created. You have to define constructor before the compenent mounted. When implementing the constructor for  React.Component subclass, you should call super() before any other statement. You should not call setState() in the constructor but you can assign the initial state to this.state directly in constructor and I assign value  items:[ ] as an empty array .

Yes ! now we are ready to set any value or URL data in an empty array with the help of setState() method.

componentDidMount() is invoked immediately after a component is
mounted means component has been loaded to the DOM.
 componentDidMount() {
    let url = "sample.json";          
    fetch(url)                             //fetch url                                                                                       
      .then(result => result.json())      //promise
      .then(json => {
        this.setState({               // set state data :result as json data
          items: json,
        })
      })
  }

In this code, We want to fetch url data or API data so we call fetch() method with url

 let url = "sample.json";          
    fetch(url)

or you can directly pass url as a string

 fetch("sample.json") 

you can fetch any url , I created a simple json file in public folder which has user data in json format and we are fetching data from this file. In real time this will be an actual url of API.

 Fetching data from URL that returns data as a json. And then return promise containing the response from the fetch request. This response is an object. To get json object out of this response call json() method.

Now you can set this json data to the items array with the help of setState() method.

So it’s too easy to fetch url. Right?

Last step is render the data with map method. You can see code below:

  render() {
    var { items } = this.state;
    if (!items) {
      return <h1>loading....</h1>;
    } else {
      return (
        <>
          <>
            {items.map(item => (
              <div style={{ width: '50%'}}>

                <div> <img alt='user' src={item.gender === 'M' ? '/image/male .png' :
                 '/image/female.png'} style={{ width: "100px", marginLeft: "5px" }} />
                </div>

                <br />
                <span>Name: {item.name}</span> <br />
             Age: {item.age}<br />
             Gender: {item.gender}<br />
                <hr /></div>

            ))}
          </>
        </>
      )
    }
  }

Never forget to export this component

export default App;

entire code are shown below :

index.html

<!DOCTYPE html>
<html lang="en">

<head>
</head>

<body>
  <div id="root"></div>
</body>

</html>

Index.js

import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';

ReactDOM.render(
<App/>, document.getElementById('root')
);

App.js

import React from 'react';


class App extends React.Component {
  constructor() {
    super();
    this.state = {
      items: [],
    }
  }
  componentDidMount() {
    let url = "sample.json";          //fetch url
    fetch(url)
      .then(result => result.json())      //promise
      .then(json => {
        this.setState({               // set state data :result as json data
          items: json,
        })
      })
  }

  render() {
    var { items } = this.state;
    if (!items) {
      return <h1>loading....</h1>;
    } else {
      return (
        <>
          <>
            {items.map(item => (
              <div style={{ width: '50%'}}>

                <div> <img alt='user' src={item.gender === 'M' ? '/image/male .png' :
                 '/image/female.png'} style={{ width: "100px", marginLeft: "5px" }} />
                </div>

                <br />
                <span>Name: {item.name}</span> 
                <br />
             Age: {item.age}<br />
             Gender: {item.gender}<br />
                <hr /></div>

            ))}
          </>
        </>
      )
    }
  }
}

export default App;

For run this app, navigate to the app folder and use command:

npm start

you will see the output in your browser.




check this complete code

thanks for reading . try this simple app and free to comment your questions and feedback.

 



Comments