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

276
Visualizações
unable to save to array react state from response from server

Hi I'm trying to save my response.data to my array state of react but it never stores the correct array but when I do a temporary array it works.

Any help would be appreciated, thanks!

 const [allstudentlist, setAllStudentlist] = useState([]);

await Axios.post(currentUrl, params).then((res) => {
  // if res.data[0][]
  // if res data is there then ;
  if (res.data["error"]) {
    alert(res.data["error"]);
  } else {
    // alert("Register Successful");
    // console.log(res.data[0]);
    console.log(res.data);
    // works
    let temp = res.data;
    setAllStudentlist(...temp);
    // works
    console.log(temp);
    // returns an empty array
    console.log(allstudentlist);
  }
});

Reponse data

reponse data

I tried to test as well with a fake api but it looks like there is an issue with setting Arrays at react

I tried to test with codeSandbox as well with a fake API and it does not work

import "./styles.css";
import React, { Component, useState, useEffect } from "react";

import Axios from "axios";
export default function App() {
  const [array2, setArray] = useState([]);

  function handleClick() {
    Axios.get("https://finalspaceapi.com/api/v0/character/?limit=2").then(
      function (response) {
        console.log(response.data);
        setArray(response.data);
        console.log(array2);
      }
    );
  }
  return (
    <div className="App">
      <h1>Hello CodeSandbox</h1>
      <h2>Start editing to see some magic happen!</h2>
      <button onClick={handleClick}></button>
    </div>
  );
}
over 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

You cannot see the updated values right after the set state as it is an async function. The way you set values is fine. Move the console log;

Outside of handleClick

  function handleClick() {
    Axios.get("https://finalspaceapi.com/api/v0/character/?limit=2").then(
      function (response) {
        console.log(response.data);
        setArray(response.data);
      }
    );
  }

  console.log(array2);

OR

Keep it inside a useEffect with a dependency

  useEffect(() => {
    console.log(array2);
  }, [array2]);
over 4 years ago · Santiago Trujillo 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