Company logo
  • Jobs
  • Bootcamp
  • About Us
  • For professionals
    • Home
    • Jobs
    • Courses and challenges
    • Questions
    • Teachers
    • Bootcamp
  • For business
    • Home
    • Our process
    • Plans
    • Assessments
    • Payroll
    • Blog
    • Sales
    • Calculator

0

118
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>
  );
}
9 months 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]);
9 months ago · Santiago Trujillo Report
Answer question
Find remote jobs