Introduction
When working with APIs we oftentimes need to ship knowledge to the server for processing. For instance, if we’ve got a listing of to-dos and need to add to it, maybe by means of a type submission, we use POST HTTP requests to ship a request with a payload for processing and potential persistence.
On this article, we’ll learn to carry out POST HTTP requests in React utilizing two commonplace approaches: the Fetch API and Axios. We will even get to understand how to do that in useful and class-based elements.
Utilizing the Fetch API, sending a POST HTTP request with React is as straightforward as:
fetch('/myserver.endpoint', {
methodology: 'POST',
physique: JSON.stringify({
})
headers: {
'Content material-type': 'utility/json; charset=UTF-8',
},
})
.then((response) => response.json())
.then((knowledge) => {
console.log(knowledge);
})
.catch((err) => {
console.log(err.message);
});
Axios offers us with a sublime various to ship HTTP POST requests:
axios.publish('/myserver.endpoint', {
})
.then((response) => {
console.log(response.knowledge);
})
.catch((error) => {
console.log(error);
})
If you would like to study extra about these approaches and the way they work – please learn the remainder of the information!
What’s a POST HTTP Request?
Because the title implies, POST requests are used to publish knowledge to an endpoint – which then sometimes processes it and saves it in a database. This knowledge might come from a type, be saved in an object, or be obtained in one other manner – nevertheless it’s sometimes transformed right into a JSON illustration for the REST API to eat.
Sending HTTP requests with any verb is made easy by the Fetch API (built-in) and libraries resembling Axios. The Fetch API is a built-in browser methodology for performing HTTP requests, whereas Axios is an exterior package deal we should set up in our challenge earlier than utilizing.
Selecting between these is as much as you. The Fetch API is extra verbose and would not work with asynchronous requests, however Axios is an exterior dependency. Even so – many desire working with Axios fairly than the Fetch API. We’ll cowl each.
Each strategies have benefits and downsides, however you will need to be aware that they’ll deal with the usual HTTP verbs – POST
, GET
, PUT
, PATCH
, DELETE
.
Observe: As beforehand acknowledged, we’ll learn to carry out POST
requests with useful elements utilizing the Fetch API and Axios strategies, after which in class-based elements utilizing the JSON Placeholder Free Pretend Posts REST API.
In our occasion, we’ll work a listing of posts that we’ve got already fetched from a mock API. We’ll create a type that takes the title and physique of a brand new publish, and as soon as submitted, sends a POST request to the mock server for processing:
import { useState, useEffect } from 'react';
const App = () => {
const [posts, setPosts] = useState([]);
useEffect(() => {
fetch('https://jsonplaceholder.typicode.com/posts?_limit=5')
.then((res) => res.json())
.then((knowledge) => {
console.log(knowledge);
setPosts(knowledge);
})
.catch((err) => {
console.log(err.message);
});
}, []);
return (
<>
<div className="add-post-container">
<type>
<enter sort="textual content" className="form-control" />
<textarea className="form-control" cols="10" rows="8"></textarea>
<button sort="submit">Add Put up</button>
</type>
</div>
<div className="posts-container">
{posts.map((publish) => {
return (
<div className="post-card" key={publish.id}>
<h2 className="post-title">{publish.title}</h2>
<p className="post-body">{publish.physique}</p>
<div className="button">
<div className="delete-btn">Delete</div>
</div>
</div>
);
})}
</div>
</>
);
};
export default App;
Let’s now make the shape useful in order that we are able to add knowledge to the publish lists on our web site as soon as the shape is submitted.
How To Carry out POST HTTP Request in React’s Practical Part
We are able to now carry out HTTP requests in useful elements because of the introduction of hooks in React. Beforehand, useful elements had been solely used for rendering UI.
A useful part is created when a JavaScript operate (both customary or ES6) returns a React aspect (JSX).
Moderately than utilizing the state object within the constructor methodology as with class-based elements, we now use React hooks resembling useState()
to retailer our knowledge earlier than passing it into the unique knowledge.
How To Carry out POST HTTP Request in React’s Practical Part With Fetch API
As a result of the Fetch API is a built-in browser methodology that returns a Promise
, we use the .then()
and .catch()
strategies to deal with success and failure. It additionally accepts a compulsory argument, which is the URL of the useful resource/API into which we need to POST knowledge, in addition to an argument indicating the HTTP request, which in our case is POST
:
import { useState, useEffect } from 'react';
const App = () => {
const [posts, setPosts] = useState([]);
const [title, setTitle] = useState('');
const [body, setBody] = useState('');
const handleSubmit = (e) => {
e.preventDefault();
fetch('https://jsonplaceholder.typicode.com/posts', {
methodology: 'POST',
physique: JSON.stringify({
title: title,
physique: physique,
userId: Math.random().toString(36).slice(2),
}),
headers: {
'Content material-type': 'utility/json; charset=UTF-8',
},
})
.then((res) => res.json())
.then((publish) => {
setPosts((posts) => [post, ...posts]);
setTitle('');
setBody('');
})
.catch((err) => {
console.log(err.message);
});
};
return (
);
};
export default App;
Within the code above, we created a way that we’ll hyperlink to the shape in order that it’s triggered when the submit button of the shape is clicked. We began by utilizing e.preventDefault()
to stop the web page from reloading when submitting the shape, which is normally what you need to occur, however would not work as nicely for our demo:
const handleSubmit = (e) => {
e.preventDefault();
};
Trying on the fetch()
name, we added the URL as the primary obligatory parameter, and the second parameter takes within the request methodology (POST), the physique
, and the header
:
physique
– accommodates the information we need to ship to the API endpoint, which we should stringify, turning it right into a text-based JSON illustration.header
– specifies the content material sort, which in our case isutility/json
, since our payload is represented as a JSON string:
const handleSubmit = (e) => {
e.preventDefault();
fetch('https://jsonplaceholder.typicode.com/posts', {
methodology: 'POST',
physique: JSON.stringify({
title: title,
physique: physique,
userId: Math.random().toString(36).slice(2),
}),
headers: {
'Content material-type': 'utility/json; charset=UTF-8',
},
})
};
Lastly, as a result of this methodology returns a Promise
, we’ll extract the JSON contents out of it (response of the server), up to date the posts
state to incorporate the brand new knowledge.
To deal with errors, we additionally used the .catch()
methodology:
Try our hands-on, sensible information to studying Git, with best-practices, industry-accepted requirements, and included cheat sheet. Cease Googling Git instructions and truly study it!
const handleSubmit = (e) => {
e.preventDefault();
fetch({...})
.then((res) => res.json())
.then((publish) => {
setPosts((posts) => [post, ...posts]);
setTitle('');
setBody('');
})
.catch((err) => {
console.log(err.message);
});
};
Warning: Sometimes, you will not retailer and course of knowledge on the front-end like we’re, however for the reason that mock API we’re working with will not really save and return the brand new publish – we’re artificially including it to the listing it does return from the primary GET request. As soon as the publish is saved within the database – we are able to make one other request to the back-end to produce the response to point out to the consumer. That is additionally why the default conduct of the shape submission is to reload the web page – which might set off the preliminary fetch()
GET request and show the brand new publish alongside the previous ones, robotically.
How To Carry out POST HTTP Request in React’s Practical Part With Axios
We defined find out how to carry out POST requests with the Fetch API within the earlier part. Now, let’s modify the handleSubmit()
methodology and carry out POST requests with Axios as an alternative.
Axios is an HTTP consumer library that makes use of guarantees to make it straightforward to ship asynchronous HTTP requests to REST endpoints. As a result of it’s an exterior library, we should first set up it in our challenge by operating the next command within the listing of our challenge:
$ npm set up axios
As soon as we have efficiently put in Axios, we are able to proceed to carry out our POST request:
const handleSubmit = (e) => {
e.preventDefault();
axios
.publish('https://jsonplaceholder.typicode.com/posts', {
title: title,
physique: physique,
})
.then((res) => {
setPosts((posts) => [res.data, ...posts]);
setTitle('');
setBody('');
})
.catch((err) => {
console.log(err.message);
});
};
Trying on the code above, it is simpler and requires much less syntax than the Fetch API, as we now not must convert to JSON, work with headers and even stringify our knowledge. This boilerplate is abstracted away by Axios.
How To Carry out POST HTTP Request in React’s Class Part
POST requests in school elements are dealt with otherwise than in useful elements as a result of we now not use React hooks and as an alternative use the state
object.
A category part is an ES6 class that returns JSX and requires React extensions.
How To Carry out POST HTTP Request in React’s Class Part With Fetch API
The request is similar to that of useful elements. The one areas we’d discover some variations are when storing knowledge in state
and when utilizing state
values as a result of we’re now not utilizing the useState()
hook:
import React, { Part } from 'react';
class App extends Part {
constructor(props) {
tremendous(props);
this.state = {
posts: [],
};
}
handleSubmit = (e) => {
e.preventDefault();
fetch('https://jsonplaceholder.typicode.com/posts', {
methodology: 'POST',
physique: JSON.stringify({
title: this.state.title,
physique: this.state.physique,
userId: Math.random().toString(36).slice(2),
}),
headers: {
'Content material-type': 'utility/json; charset=UTF-8',
},
})
.then((response) => response.json())
.then((knowledge) => {
this.setState({ posts: [data, ...this.state.posts] });
this.setState({ title: '' });
this.setState({ physique: '' });
})
.catch((err) => {
console.log(err.message);
});
};
render() {
const { posts, title, physique } = this.state;
return (
);
}
}
export default App;
This time, we now not declare strategies with the const
key phrase. As an alternative, prefix them with this
. This methodology can be triggered when the shape’s submit button is clicked. Since it is a type, we began by utilizing e.preventDefault()
to stop the web page from reloading when the shape is submitted:
handleSubmit = (e) => {
e.preventDefault();
};
Similar to we discovered earlier, the Fetch API takes in two parameters. One is the URL, whereas the second accommodates choices just like the request methodology (POST
), physique
, which is the data we’re posting (have to be stringified), after which the headers
:
handleSubmit = (e) => {
e.preventDefault();
fetch('https://jsonplaceholder.typicode.com/posts', {
methodology: 'POST',
physique: JSON.stringify({
title: this.state.title,
physique: this.state.physique,
userId: Math.random().toString(36).slice(2),
}),
headers: {
'Content material-type': 'utility/json; charset=UTF-8',
},
})
};
Realizing this can be a promise, we are able to now connect the .then()
methodology to deal with success and the .catch()
methodology to deal with a state of affairs if there’s an error or failure within the HTTP request.
How To Carry out POST HTTP Request in React’s Class Part With Axios
We’ve got seen find out how to carry out POST
HTTP requests in class-based elements. That is similar to Axios, as all we’ve got to do is set up Axios after which change the handleSubmit()
methodology, so we now use Axios fairly than Fetch API:
handleSubmit = (e) => {
e.preventDefault();
axios
.publish('https://jsonplaceholder.typicode.com/posts', {
title: this.state.title,
physique: this.state.physique,
userId: 1,
})
.then((response) => {
this.setState({ posts: [response.data, ...this.state.posts] });
this.setState({ title: '' });
this.setState({ physique: '' });
})
.catch((error) => console.log(error));
};
Conclusion
On this information, we discovered find out how to use the 2 main strategies in React to carry out POST HTTP requests. We additionally noticed how they may very well be finished in each useful and class-based elements, so this text can serve us regardless of what’s utilized in our challenge.