Introduction
When working with APIs we oftentimes need to ship knowledge to the server for processing. For instance, if now we have an inventory of to-dos and need to add to it, maybe by way of a kind submission, we use POST HTTP requests to ship a request with a payload for processing and potential persistence.
On this article, we are going to learn to carry out POST HTTP requests in React utilizing two commonplace approaches: the Fetch API and Axios. We may 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', {
technique: 'POST',
physique: JSON.stringify({
})
headers: {
'Content material-type': 'software/json; charset=UTF-8',
},
})
.then((response) => response.json())
.then((knowledge) => {
console.log(knowledge);
})
.catch((err) => {
console.log(err.message);
});
Axios supplies us with a sublime different to ship HTTP POST requests:
axios.submit('/myserver.endpoint', {
})
.then((response) => {
console.log(response.knowledge);
})
.catch((error) => {
console.log(error);
})
If you would like to be taught 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 submit knowledge to an endpoint – which then usually processes it and saves it in a database. This knowledge may come from a kind, be saved in an object, or be obtained in one other approach – nevertheless it’s usually 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 corresponding to Axios. The Fetch API is a built-in browser technique for performing HTTP requests, whereas Axios is an exterior package deal we should set up in our venture 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 choose working with Axios somewhat than the Fetch API. We’ll cowl each.
Each strategies have benefits and drawbacks, however it is very important observe that they will deal with the usual HTTP verbs – POST
, GET
, PUT
, PATCH
, DELETE
.
Notice: As beforehand acknowledged, we are going to 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 Faux Posts REST API.
In our occasion, we’ll work an inventory of posts that now we have already fetched from a mock API. We’ll create a kind that takes the title and physique of a brand new submit, 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">
<kind>
<enter sort="textual content" className="form-control" />
<textarea className="form-control" cols="10" rows="8"></textarea>
<button sort="submit">Add Submit</button>
</kind>
</div>
<div className="posts-container">
{posts.map((submit) => {
return (
<div className="post-card" key={submit.id}>
<h2 className="post-title">{submit.title}</h2>
<p className="post-body">{submit.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 will add knowledge to the submit lists on our web site as soon as the shape is submitted.
How To Carry out POST HTTP Request in React’s Useful Element
We will now carry out HTTP requests in useful elements due to the introduction of hooks in React. Beforehand, useful elements had been solely used for rendering UI.
A useful element is created when a JavaScript perform (both normal or ES6) returns a React factor (JSX).
Fairly than utilizing the state object within the constructor technique as with class-based elements, we now use React hooks corresponding to useState()
to retailer our knowledge earlier than passing it into the unique knowledge.
How To Carry out POST HTTP Request in React’s Useful Element With Fetch API
As a result of the Fetch API is a built-in browser technique 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', {
technique: 'POST',
physique: JSON.stringify({
title: title,
physique: physique,
userId: Math.random().toString(36).slice(2),
}),
headers: {
'Content material-type': 'software/json; charset=UTF-8',
},
})
.then((res) => res.json())
.then((submit) => {
setPosts((posts) => [post, ...posts]);
setTitle('');
setBody('');
})
.catch((err) => {
console.log(err.message);
});
};
return (
);
};
export default App;
Within the code above, we created a technique that we’ll hyperlink to the shape in order that it’s triggered when the submit button of the shape is clicked. We began through the use of e.preventDefault()
to stop the web page from reloading when submitting the shape, which is often what you need to occur, however would not work as effectively for our demo:
const handleSubmit = (e) => {
e.preventDefault();
};
Wanting on the fetch()
name, we added the URL as the primary necessary parameter, and the second parameter takes within the request technique (POST), the physique
, and the header
:
physique
– accommodates the info 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 issoftware/json
, since our payload is represented as a JSON string:
const handleSubmit = (e) => {
e.preventDefault();
fetch('https://jsonplaceholder.typicode.com/posts', {
technique: 'POST',
physique: JSON.stringify({
title: title,
physique: physique,
userId: Math.random().toString(36).slice(2),
}),
headers: {
'Content material-type': 'software/json; charset=UTF-8',
},
})
};
Lastly, as a result of this technique 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()
technique:
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 be taught it!
const handleSubmit = (e) => {
e.preventDefault();
fetch({...})
.then((res) => res.json())
.then((submit) => {
setPosts((posts) => [post, ...posts]);
setTitle('');
setBody('');
})
.catch((err) => {
console.log(err.message);
});
};
Warning: Usually, you will not retailer and course of knowledge on the front-end like we’re, however because the mock API we’re working with will not really save and return the brand new submit – we’re artificially including it to the listing it does return from the primary GET request. As soon as the submit is saved within the database – we will make one other request to the back-end to provide the response to indicate 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 submit alongside the previous ones, robotically.
How To Carry out POST HTTP Request in React’s Useful Element With Axios
We defined tips on how to carry out POST requests with the Fetch API within the earlier part. Now, let’s modify the handleSubmit()
technique and carry out POST requests with Axios as a substitute.
Axios is an HTTP shopper 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 venture by operating the next command within the listing of our venture:
$ npm set up axios
As soon as we have efficiently put in Axios, we will proceed to carry out our POST request:
const handleSubmit = (e) => {
e.preventDefault();
axios
.submit('https://jsonplaceholder.typicode.com/posts', {
title: title,
physique: physique,
})
.then((res) => {
setPosts((posts) => [res.data, ...posts]);
setTitle('');
setBody('');
})
.catch((err) => {
console.log(err.message);
});
};
Wanting on the code above, it’s miles simpler and requires much less syntax than the Fetch API, as we not have to 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 Element
POST requests at school elements are dealt with otherwise than in useful elements as a result of we not use React hooks and as a substitute use the state
object.
A category element is an ES6 class that returns JSX and requires React extensions.
How To Carry out POST HTTP Request in React’s Class Element With Fetch API
The request is similar to that of useful elements. The one areas we might discover some variations are when storing knowledge in state
and when utilizing state
values as a result of we’re not utilizing the useState()
hook:
import React, { Element } from 'react';
class App extends Element {
constructor(props) {
tremendous(props);
this.state = {
posts: [],
};
}
handleSubmit = (e) => {
e.preventDefault();
fetch('https://jsonplaceholder.typicode.com/posts', {
technique: 'POST',
physique: JSON.stringify({
title: this.state.title,
physique: this.state.physique,
userId: Math.random().toString(36).slice(2),
}),
headers: {
'Content material-type': 'software/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 not declare strategies with the const
key phrase. As a substitute, prefix them with this
. This technique shall be triggered when the shape’s submit button is clicked. Since it is a kind, we began through the use of 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 technique (POST
), physique
, which is the information we’re posting (have to be stringified), after which the headers
:
handleSubmit = (e) => {
e.preventDefault();
fetch('https://jsonplaceholder.typicode.com/posts', {
technique: 'POST',
physique: JSON.stringify({
title: this.state.title,
physique: this.state.physique,
userId: Math.random().toString(36).slice(2),
}),
headers: {
'Content material-type': 'software/json; charset=UTF-8',
},
})
};
Realizing this can be a promise, we will now connect the .then()
technique to deal with success and the .catch()
technique to deal with a state of affairs if there may be an error or failure within the HTTP request.
How To Carry out POST HTTP Request in React’s Class Element With Axios
We now have seen tips on how to carry out POST
HTTP requests in class-based elements. That is similar to Axios, as all now we have to do is set up Axios after which substitute the handleSubmit()
technique, so we now use Axios somewhat than Fetch API:
handleSubmit = (e) => {
e.preventDefault();
axios
.submit('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 tips on how to use the 2 main strategies in React to carry out POST HTTP requests. We additionally noticed how they could possibly be executed in each useful and class-based elements, so this text can serve us regardless of what’s utilized in our venture.