Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

145
Visualizações
Not able to update API method: PUT in a function update(). Not able to update all the attributes of a particular ID
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?

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

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");
            })
        })
}
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda