loading...

How to GET data from an API in React JS

damish profile image Damish Updated on ・2 min read

Hello everyone today I’m going to show you how to implement HTTP GET action of any API inside a React JS application. For this, we use fetch() function.

Here the input parameter passed for the fetch function is an API URL. And the response from API is a JSON type response.We can set the response data to a state variable using this.setState({ }) .Here I have used sensors array list to store the data comming from fetch() method.

The structure of the fetch function is as follows,

import React , {Component} from 'react';
class App extends Component {

state = {
loading: true,
sensors: null,
};
componentDidMount() {
fetch('api.example.com')
.then((response) => {
return response.json();
})
.then((data) => {
this.setState({
sensors: data,
loading: false
})
console.log(data);
});
}

Let us come to the rendering part of the component in index.html,

Here we can add a loading screen using another Boolean state variable (this.state.loading) which is displayed until data is been fetched from the API as follows,

*Note: Here I have used bootstrap 4 for the project.If you don’t use bootstrap css, remove << className={“”} >> attributes in

tags or Instead use only pure tags and test.

render() {
if (this.state.loading) { //this content is displayed when (loading == true)
return (

            <div className={"row mt-4 justify-content-center"}>
                <div className="spinner-border" role="status"></div>
            </div>


            <div className={"row mt-4 justify-content-center"}>
                <h1>Fetching data...please wait</h1>
            </div>


        </div>
    )
}

return (

{this.state.sensors.map((value) =&gt; {


    return (

               <h5>Sid: {value.sid} </h5>
               <h4>Co2 Level: {value.co2Level}</h4>

               <h4>Smoke Level: {value.smokeLevel}</h4>
               <h5>Floor No: {value.floorNo}</h5>
               <h5>Room No: {value.roomNo}</h5>

)

 }

)

}

I hope now you are clear about the fetch function and its implementation. If you have any questions please comment below. Stay connected with our blog for more posts like this.

Alt Text

Posted on by:

damish profile

Damish

@damish

Undergraduate 🎓| BSc (Hons) in Information Technology specializing in Software Engineering at SLIIT FrontendDev💻 | UI/UX | Happy Coding 🥇

Discussion

markdown guide