Home > Back-end >  Unable to save to array React state from the response from the server
Unable to save to array React state from the response from the server

Time:05-14

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.

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);
  }
});

Response data

Response data

I tried to test as well with a fake API, but it looks like there is an issue with setting Arrays in 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>
  );
}

How can I fix it?

CodePudding user response:

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]);
  • Related