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

250
Visualizações
How to update the state after a data update through an API request in React?

I have a small problem. I have this fetch data in one component which is working perfectly:

const [item, setItem] = useState([]);
  const [loading, setLoading] = useState(false);

  useEffect(() => {
    setLoading(true);
    fetch("https://api/products")
      .then((response) => response.json())
      .then((data) => setItem(data))
      .finally(() => setLoading(false));
  }, []);

Then I have this POST in a different component:

const handleSubmit = async (e) => {
    e.preventDefault();
    try {
      await fetch("https://api/products", {
        method: "POST",
        headers: { admin: "true", "Content-Type": "application/json" },
        body: JSON.stringify(body),
      });
    } catch (error) {
      console.log("error");
    }
  };

How I can get the new data of the first component after using POST without reloading the web page?

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

0

You need to be able to append that new data, body inside item array, means you need to call this setItem(prev => [...prev, body]) in your try-catch, something like:

const handleSubmit = async (e) => {
    e.preventDefault();
    try {
      await fetch("https://api/products", {
        method: "POST",
        headers: { admin: "true", "Content-Type": "application/json" },
        body: JSON.stringify(body),
      });
      setItem(prev => [...prev, body]); // here you add the new data
    } catch (error) {
      console.log("error");
    }
  };

Now how you would access this setItem function? Well if the component that's making the POST request is a child of the component where you have this line const [item, setItem] = useState([]), you could pass setItem as a props.

If it's not the case, either you move this const [item, setItem] = useState([]) inside a component that's parent of all those components and pass down what you need as props or use a state management solution like the context API.

about 4 years ago · Juan Pablo Isaza Relatório

0

You must call the function again when response is true. I mean your function when getting data.

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