DEV Community

Damish
Damish

Posted on • Updated on

 

How to GET data from an API in React JS

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>
Enter fullscreen mode Exit fullscreen mode

)

 }
Enter fullscreen mode Exit fullscreen mode

)

}

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

Top comments (0)

typescript

11 Tips That Make You a Better Typescript Programmer

1 Think in {Set}

Type is an everyday concept to programmers, but it’s surprisingly difficult to define it succinctly. I find it helpful to use Set as a conceptual model instead.

#2 Understand declared type and narrowed type

One extremely powerful typescript feature is automatic type narrowing based on control flow. This means a variable has two types associated with it at any specific point of code location: a declaration type and a narrowed type.

#3 Use discriminated union instead of optional fields

...

Read the whole post now!