How to make a post request in React hooks
Learn, how to make a post request in react hooks using fetch API.
Making a post request in React hooks
This below example sends an http post request to the json placeholder api using fetch where useState()
hook is used to store the user entered data.
import React, { useState } from "react";
function App() {
const [title, setTitle] = useState("");
const [body, setBody] = useState("");
const onTitleChange = e => setTitle(e.target.value); const onBodyChange = e => setBody(e.target.value);
const handleSubmit = e => {
e.preventDefault();
const data = { title, body };
const requestOptions = {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(data)
};
fetch("https://jsonplaceholder.typicode.com/posts", requestOptions) .then(response => response.json()) .then(res => console.log(res)); };
return (
<div className="App">
<form>
<input placeholder="Title" value={title} onChange={onTitleChange} required /> <textarea placeholder="Body" value={body} onChange={onBodyChange} required /> <button type="submit" onClick={handleSubmit}>
Create Post
</button>
</form>
</div>
);
}
export default App;
In the above code, we first imported useState()
hook from the react
then we initialized a state inside the App
component which are title
, body
.
The onTitleChange()
and onBodyChange()
functions are used to set the user entered data to title
and body
properties.
If we click on a Create Post
button it will call the handleSubmit()
function, which sends a post request to the api.