HTTP methods with Hooks
13 May, 2020
BackGET
This fetches all the data from the http:localhost/3001/data
endpoint. Note that data fetched type is an object, but data is read with the .map()
method as an array.
The second argument in useEffect
is [data]
. This is to 'refresh' the state every time an item is created, updated, and deleted.
import React, { useState, useEffect } from "react";
const Get = () => {
const [data, setData] = useState([]);
useEffect(() => {
const getData = async () => {
const res = await fetch(`http:localhost/3001/data`);
setData(res.data);
};
getData();
}, [data]);
return (
<div>
{data.map((x) => (
<p key={x.id}>{x.name}</p>
))}
</div>
);
};
export default Get;
POST
Post adds a new item to your list.
import React, { useState } from "react";
const Post = () => {
const [name, setName] = useState("");
const postData = (e) => {
e.preventDefault();
fetch(`http://localhost:3001/data`, {
method: "POST",
body: JSON.stringify({
name: `${name}`,
}),
headers: {
"Content-type": "application/json; charset=UTF-8",
},
})
.then((response) => response.json())
.then((json) => console.log(json));
setName("");
};
return (
<div>
<form>
<input
value={name}
type="text"
onChange={(e) => setName(e.target.value)}
/>
<button onClick={postData}>
Create
</button>
</form>
</div>
);
};
export default Post;
PUT
The route for the item must be included in the link.
Eg: http://localhost:3001/data/2
This updates the second item in the list.
import React, { useState } from "react";
const id = 1;
const Put = () => {
const [name, setName] = useState(name);
const putData = (e) => {
e.preventDefault();
fetch(`http://localhost:3001/data/${id}`, {
method: "PUT",
body: JSON.stringify({
name: `${name}`,
}),
headers: {
"Content-type": "application/json; charset=UTF-8",
},
})
.then((response) => response.json())
.then((json) => console.log(json));
setName("");
};
return (
<div>
<form>
<input
type="text"
value={name}
onChange={(e) => setName(e.target.value)}
/>
<button onClick={putData}>
Update
</button>
</form>
</div>
);
};
export default Put;
DELETE
Similar to PUT, the route of the item needs to be included.
Eg: http://localhost:3001/data/2
This deletes the second item in the list.
import React from "react";
const id = 1;
const Delete = () => {
const deleteData = (e) => {
e.preventDefault();
fetch(`http://localhost:3001/data/${id}`, {
method: "DELETE",
});
};
return (
<form>
<button onClick={deleteData}>
Delete
</button>
</form>
);
};
export default Delete;
Reference
Back