Company logo
  • Empleos
  • Bootcamp
  • Acerca de nosotros
  • Para profesionales
    • Inicio
    • Empleos
    • Cursos y retos
    • Preguntas
    • Profesores
    • Bootcamp
  • Para empresas
    • Inicio
    • Nuestro proceso
    • Planes
    • Pruebas
    • Nómina
    • Blog
    • Calculadora

0

116
Vistas
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>
  );
}
9 months ago · Santiago Trujillo
1 Respuestas
Responde la pregunta

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]);
9 months ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar empleo Planes Nuestro proceso Comercial
Legal
Términos y condiciones Política de privacidad
© 2023 PeakU Inc. All Rights Reserved.