Http post call using window.fetch method in react function 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 Post call, once component mounted.

Create request body

The post request expect header and request body and config object if required by the backend system. we are going to provide to the API and newly created object to persist new content which can be used for further processing.
Request body
 1 {
 2 	comment: "This is my first comment !",
 3 	date: "2022-04-13",
 4 	id: 6,
 5 	user: "React"
 6 }

Making post request using fetch method

To make post request, we have to provide header with content type and actual body which is specified above. The request body object must be in string form, hence before passing to API its needs to convert into string using JSON.stringify() method.
Making post request using fetch method
 1 const submitPost = async (post) => {
 2     let response = await fetch("/api/create", {
 3       method: "POST",
 4       headers: {
 5         "access-control-allow-origin": "*",
 6         "Content-type": "application/json; charset=UTF-8"
 7       },
 8       body: JSON.stringify(post)
 9     });
 10     console.log(response.data);
 11 }
In the above example, a handler function is define using fat arrow function that makes http post api call using async and await keywords by passing a three parameters, an API, option object and request object as body. A handler method is passed to child functional component and generate the request body using React form. It can be either stateful component or stateless component.
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.
Form for creating post
 1 import React, { useState } from 'react';
 2 
 3 function Post(props) {
 4 
 5     const [post, setState] = useState({
 6         content: '',
 7         date: '',
 8         user: 'React'
 9     });
 10 
 11     // handler methods
 12     const handleChange = (e) => {
 13         setState({
 14             ...post,
 15             [e.target.name]: e.target.value
 16         })
 17     };
 18 
 19     const submitForm = (e) => {
 20         e.preventDefault();
 21         props.submitPost(post);
 22     };
 23 
 24     return (
 25         <div id="login">
 26             <form onSubmit={submitForm}>
 27                 <div>
 28                     <label htmlFor="content">Content : </label>
 29                     <input type="text" id="content" name="content"
 30                         defaultValue={post.content}
 31                         placeholder="Content"
 32                         onChange={(e) => handleChange(e)}
 33                     />
 34                 </div>
 35                 <div>
 36                     <label htmlFor="date">Date : </label>
 37                     <input type="date" id="date" name="date"
 38                         defaultValue={post.date}
 39                         placeholder="date"
 40                         onChange={(e) => handleChange(e)}
 41                     />
 42                 </div>
 43                 <div>
 44                     <label htmlFor="user">Posted By : </label>
 45                     <input type="user" id="user" name="user"
 46                         defaultValue={post.user}
 47                         placeholder="user"
 48                         onChange={(e) => handleChange(e)}
 49                     />
 50                 </div>
 51                 <input type="submit" defaultValue="Submit" />
 52             </form>
 53         </div >
 54     );
 55 }
 56 export default Post;
 57 
In the above example, a functional component is define with state and handler method. A handler method called when an input element value changed that update the state of component. A component calls a parent class handler method when form submitted by clicking submit button. Add this component in the parent component render() method, if it is class component and if it is function component it should be part of return statement. It can be achieve by passing the handler method specified below in the App component.
Adding component in function component
 1 import React from 'react';
 2 import Post from './components/post';
 3 
 4 function App() {
 5   const submitPost = async (post) => {
 6     let response = await fetch('/api/create', {
 7       method: 'POST',
 8       headers: {
 9         'access-control-allow-origin': '*',
 10         'Content-type': 'application/json; charset=UTF-8',
 11       },
 12       body: JSON.stringify(post),
 13     });
 14     console.log(response.data);
 15   };
 16 
 17   return (
 18     <div>
 19       <Post submitPost={submitPost} />
 20     </div>
 21   );
 22 }
 23 
 24 export default App;
In the above example, a functional component App define with handler method that calls http post api by specifying a request object as body. A child component Post is added to the template by specifying a handler function as property that will be called on form submission.
Adding component in class component using this keyword
 1 <Post submitPost={ this.submitPost } />
If App component is define as class component, a component must be added in the render() method and a handler method specified with this keyword.
Privacy Policy
Terms of Service
Disclaimer
Contact us
About us