[ad_1]
Introduction
When working with APIs we oftentimes wish to ship information to the server for processing. For instance, if we have now a listing of to-dos and wish to add to it, maybe via 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 may also get to understand how to do that in practical and class-based parts.
Utilizing the Fetch API, sending a POST HTTP request with React is as simple as:
fetch('/myserver.endpoint', {
methodology: 'POST',
physique: JSON.stringify({
})
headers: {
'Content material-type': 'utility/json; charset=UTF-8',
},
})
.then((response) => response.json())
.then((information) => {
console.log(information);
})
.catch((err) => {
console.log(err.message);
});
Axios supplies us with a chic various to ship HTTP POST requests:
axios.publish('/myserver.endpoint', {
})
.then((response) => {
console.log(response.information);
})
.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 information to an endpoint – which then sometimes processes it and saves it in a database. This information may come from a type, be saved in an object, or be obtained in one other method – however 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 undertaking earlier than utilizing.
Selecting between these is as much as you. The Fetch API is extra verbose and does not work with asynchronous requests, however Axios is an exterior dependency. Even so – many choose working with Axios reasonably than the Fetch API. We’ll cowl each.
Each strategies have benefits and drawbacks, however you will need to word that they will deal with the usual HTTP verbs – POST
, GET
, PUT
, PATCH
, DELETE
.
Be aware: As beforehand said, we’ll learn to carry out POST
requests with practical parts utilizing the Fetch API and Axios strategies, after which in class-based parts utilizing the JSON Placeholder Free Pretend Posts REST API.
In our occasion, we’ll work a listing of posts that we have now 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((information) => {
console.log(information);
setPosts(information);
})
.catch((err) => {
console.log(err.message);
});
}, []);
return (
<>
<div className="add-post-container">
<type>
<enter kind="textual content" className="form-control" />
<textarea className="form-control" cols="10" rows="8"></textarea>
<button kind="submit">Add Submit</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 practical in order that we will add information 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 Purposeful Element
We are able to now carry out HTTP requests in practical parts due to the introduction of hooks in React. Beforehand, practical parts had been solely used for rendering UI.
A practical element is created when a JavaScript perform (both normal or ES6) returns a React aspect (JSX).
Quite than utilizing the state object within the constructor methodology as with class-based parts, we now use React hooks resembling useState()
to retailer our information earlier than passing it into the unique information.
How To Carry out POST HTTP Request in React’s Purposeful Element 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 wish to POST information, 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 through the use of e.preventDefault()
to forestall the web page from reloading when submitting the shape, which is often what you wish to occur, however does not work as effectively for our demo:
const handleSubmit = (e) => {
e.preventDefault();
};
Trying on the fetch()
name, we added the URL as the primary necessary parameter, and the second parameter takes within the request methodology (POST), the physique
, and the header
:
physique
– comprises the information we wish to ship to the API endpoint, which we should stringify, turning it right into a text-based JSON illustration.header
– specifies the content material kind, 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 information.
To deal with errors, we additionally used the .catch()
methodology:
Take a look at 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 information 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 record it does return from the primary GET request. As soon as the publish is saved within the database – we will make one other request to the back-end to produce the response to point out to the person. That is additionally why the default habits 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 outdated ones, routinely.
How To Carry out POST HTTP Request in React’s Purposeful Element With Axios
We defined the right way 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 a substitute.
Axios is an HTTP consumer library that makes use of guarantees to make it simple 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 undertaking by operating the next command within the listing of our undertaking:
$ 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
.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’s miles simpler and requires much less syntax than the Fetch API, as we now not have to convert to JSON, work with headers and even stringify our information. This boilerplate is abstracted away by Axios.
How To Carry out POST HTTP Request in React’s Class Element
POST requests at school parts are dealt with in another way than in practical parts as a result of we now 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 practical parts. The one areas we’d discover some variations are when storing information in state
and when utilizing state
values as a result of we’re now 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', {
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((information) => {
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 through the use of e.preventDefault()
to forestall the web page from reloading when the shape is submitted:
handleSubmit = (e) => {
e.preventDefault();
};
Identical to we realized earlier, the Fetch API takes in two parameters. One is the URL, whereas the second comprises choices just like the request methodology (POST
), physique
, which is the data we’re posting (should 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',
},
})
};
Understanding it is a promise, we will now connect the .then()
methodology to deal with success and the .catch()
methodology to deal with a scenario 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 have now seen the right way to carry out POST
HTTP requests in class-based parts. That is similar to Axios, as all we have now to do is set up Axios after which substitute the handleSubmit()
methodology, so we now use Axios reasonably 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 realized the right way to use the 2 main strategies in React to carry out POST HTTP requests. We additionally noticed how they might be performed in each practical and class-based parts, so this text can serve us regardless of what’s utilized in our undertaking.
[ad_2]
Source_link