Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

148
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!