In the example below we show how to call Post API using Axios asynchronously in React functional component.
We utilise “useState” for creating a state variable pass its value to the post request:
import React, { useState } from "react";
import axios from "axios";
const PostCreate = () => {
const [title, setTitle] = useState("");
const onSubmit = async (event) => {
event.preventDefault();
await axios.post("http://localhost:4000/posts", {
title,
});
setTitle("");
};
return (
<div>
<form onSubmit={onSubmit}>
<div className="form-group">
<label>Title</label>
<input
value={title}
onChange={(e) => setTitle(e.target.value)}
className="form-control"
/>
</div>
<button className="btn btn-primary">Submit</button>
</form>
</div>
);
};
export default PostCreate;