Http get using window.fetch method in react class component
The Fetch API is built in feature provided by most modern browser on the window object which allows to us to make HTTP requests. This method returns JavaScript promise as response. It expect HTTP url endpoint to make simple http Get call, once component mounted.

Steps to make get API call

1. Add fetch API2. Update state3. Render data

Add fetch API

The fetch API call needs to be add once component gets mounted. If you are using class component its need to be add in the componentDidMount life cycle hook and if its function component it can be added using useEffect() hook.
Adding fetch API
 1 fetch("/api/getposts", {
 2       method: "GET",
 3       headers: {
 4         "access-control-allow-origin": "*",
 5         "Content-type": "application/json; charset=UTF-8"
 6       }
 7 })
In the above example, we have added relative url inside fetch() method. It is possible by configuring proxy in the package.json file of react application.
In the above example, a get api is specified as relative, a react application allows to configure base URL which can be configure in the package.json and appended before the relative url. It used when an application deployed on different environment. It allows to update server base URL for respective environment only at one place, otherwise you have to update it in all the fetch() method.

Update state

If you want to render the data in the component, it needs to store data inside component. To store data react provide state management feature to store data and when state is updated component will re-render the update state data.
Update component state
 1 fetch("/api/getposts", {
 2       method: "GET",
 3       headers: {
 4         "access-control-allow-origin": "*",
 5         "Content-type": "application/json; charset=UTF-8"
 6       }
 7     })
 8       .then(res => res.json())
 9       .then(
 10         (result) => {
 11           this.setState({
 12             isLoaded: true,
 13             items: result
 14           });
 15         }
 16       )
 17   }
In the above example, an http GET method called by passing a relative URL and option object that includes http method and headers parameters. It returns a Promise object that needs to be subscribe using then() method and converted to json using json() method that returns promise and chain with then() method that updates the state of component by specifying an object that include boolean variable and list of items.

Render data using render method

To render data on component we have to use component state and the response schema to display fields.
Render data using render method
 1 import React from 'react';
 2 import './App.css';
 3 
 4 class App extends React.Component {
 5 
 6   constructor(props) {
 7     super(props);
 8     this.state = {
 9       error: null,
 10       isLoaded: false,
 11       items: []
 12     };
 13   }
 14 
 15   componentDidMount() {
 16     fetch("/api/getposts", {
 17       method: "GET",
 18       headers: {
 19         "access-control-allow-origin": "*",
 20         "Content-type": "application/json; charset=UTF-8"
 21       }
 22     })
 23       .then(res => res.json())
 24       .then(
 25         (result) => {
 26           this.setState({
 27             isLoaded: true,
 28             items: result
 29           });
 30         },
 31         (error) => {
 32           this.setState({
 33             isLoaded: true,
 34             error
 35           });
 36         }
 37       )
 38   }
 39 
 40   render() {
 41     const { error, isLoaded, items } = this.state;
 42     if (error) {
 43       return <div>Error: {error.message}</div>;
 44     } else if (!isLoaded) {
 45       return <div>Loading...</div>;
 46     } else {
 47       return (
 48       <table>
 49         <thead>
 50           <tr>
 51             <th></th>
 52             <th>Post</th>
 53             <th>Posted by</th>
 54           </tr>
 55         </thead>
 56         <tbody>
 57           {items.map(item => (
 58             <tr key={item.id}>
 59               <td>{item.id}</td>
 60               <td>{item.content}</td>
 61               <td>{item.user}</td>
 62             </tr>
 63           ))}
 64         </tbody>
 65       </table>
 66       );
 67     }
 68   };
 69 }
 70 
 71 export default App;
In the above example, a render() method iterated list of items using map() method using JSX syntax. A key attributes uniquely identifies each records that helps to re-render item when change made, it matches the key and re-render only that records.
Privacy Policy
Terms of Service
Disclaimer
Contact us
About us