Below is a quick set of examples to show how to send HTTP POST requests from React to a backend API using the axios
HTTP client which is available on npm.
Other HTTP examples available:
With the npm CLI: npm install axios
With the yarn CLI: yarn add axios
This sends an HTTP POST request to the Reqres api which is a fake online REST api that includes a generic /api/<resource>
route that responds to POST
requests for any <resource>
with the contents of the post body and a dynamic id property. This example sends an article
object to the /api/articles
route and then assigns the id from the response to the react component state property articleId
so it can be displayed in the component render()
method.
componentDidMount() {
// Simple POST request with a JSON body using axios
const article = { title: 'React POST Request Example' };
axios.post('https://reqres.in/api/articles', article)
.then(response => this.setState({ articleId: response.data.id }));
}
Example React component at https://stackblitz.com/edit/react-http-post-request-examples-axios?file=App/PostRequest.jsx
This sends the same POST request from React using axios, but this version uses React hooks from a function component instead of lifecycle methods from a traditional React class component. The useEffect
React hook replaces the componentDidMount
lifecycle method to make the HTTP POST request when the component loads.
The second parameter to the useEffect
React hook is an array of dependencies that determines when the hook is run, passing an empty array causes the hook to only be run once when the component first loads, like the componentDidMount
lifecyle method in a class component. For more info on React hooks see https://reactjs.org/docs/hooks-intro.html.
useEffect(() => {
// POST request using axios inside useEffect React hook
const article = { title: 'React Hooks POST Request Example' };
axios.post('https://reqres.in/api/articles', article)
.then(response => setArticleId(response.data.id));
// empty dependency array means this effect will only run once (like componentDidMount in classes)
}, []);
Example React hooks component at https://stackblitz.com/edit/react-http-post-request-examples-axios?file=App/PostRequestHooks.jsx
This sends the same POST request from React using axios, but this version uses an async
function and the await
javascript expression to wait for the promises to return (instead of using the promise then()
method as above).
async componentDidMount() {
// POST request using axios with async/await
const article = { title: 'React POST Request Example' };
const response = await axios.post('https://reqres.in/api/articles', article);
this.setState({ articleId: response.data.id });
}
#react