import React, { useEffect, useState } from 'react';
import { useParams } from 'react-router-dom';
const RestaurantUpdate = () => {
const [state, setState] = useState({ name: '', email: '', address: '', rating: '' })
const [name, setName] = useState("");
const [email, setEmail] = useState("");
const [address, setAddress] = useState("");
const [rating, setRating] = useState("");
const { id } = useParams();
useEffect(() => {
fetch('http://localhost:3000/restaurant/' + id).then((response) => {
response.json().then((result) => {
console.warn(result.name);
setName(result.name);
setEmail(result.email);
setAddress(result.address);
setRating(result.rating);
})
})
}, []);
function update() {
fetch("http://localhost:3000/restaurant/" + id,
{
method: "PUT",
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(state)
}).then((result) => {
result.json().then((resp) => {
alert("Restaurant has been updated");
})
})
}
return (
<div>
<h1>Update</h1>
<div>
<input onChange={(event) => setName(event.target.value)}
placeholder="Restaurant Name" value={name} /> <br /><br />
<input onChange={(event) => setEmail(event.target.value)}
placeholder="Restaurant Email" value={email} /> <br /><br />
<input onChange={(event) => setRating(event.target.value)}
placeholder="Restaurant Rating" value={rating} /> <br /><br />
<input onChange={(event) => setAddress(event.target.value)}
placeholder="Restaurant Address" value={address} /> <br /><br />
<button onClick={() => { update() }}>Update Restaurant</button>
</div>
</div>
);
};
export default RestaurantUpdate;
Want my API to get updated. But it is not working. Attributes of that particular id is getting blank. How to update all the data of that particular id in functional components?
Maybe I have some syntax error or is there any another alternative method?
You're updating the individual pieces of state (name, email, address, rating), but sending the big piece of state (state) with your API call. This piece of state is never updated in your component. It will always send your defualt values, which are empty strings for every property.
You could pass the individual pieces of state to the API call:
function update() {
fetch("http://localhost:3000/restaurant/" + id,
{
method: "PUT",
headers: {
'Content-Type': 'application/json'
},
// use object property shorthand to avoid
// syntax like { name: name, email: email ... }
body: { name, email, address, rating }
}).then((result) => {
result.json().then((resp) => {
alert("Restaurant has been updated");
})
})
}