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

193
Views
Getting stale value of local state variable after response returned from promise

I have a react application with two buttons, which on click load user name from server. The behaviour works if I click buttons one at a time and wait for response, however, if I click both, the response from API for second button writes value to state which is stale due to which the first button gets stuck in loading state. How can I resolve this to always have latest data when promise resolves?

Code sandbox demo: https://codesandbox.io/s/pensive-frost-qkm9xh?file=/src/App.js:0-1532

import "./styles.css";
import LoadingButton from "@mui/lab/LoadingButton";
import { useRef, useState } from "react";
import { Typography } from "@mui/material";

const getUsersApi = (id) => {
  const users = { "12": "John", "47": "Paul", "55": "Alice" };
  return new Promise((resolve) => {
    setTimeout((_) => {
      resolve(users[id]);
    }, 1000);
  });
};

export default function App() {
  const [users, setUsers] = useState({});
  const availableUserIds = [12, 47];

  const loadUser = (userId) => {
    // Mark button as loading
    const updatedUsers = { ...users };
    updatedUsers[userId] = {
      id: userId,
      name: undefined,
      isLoading: true,
      isFailed: false
    };
    setUsers(updatedUsers);

    // Call API
    getUsersApi(userId).then((userName) => {
      // Update state with user name
      const updatedUsers = { ...users };
      updatedUsers[userId] = {
        ...updatedUsers[userId],
        name: userName,
        isLoading: false,
        isFailed: false
      };
      setUsers(updatedUsers);
    });
  };

  return (
    <div className="App">
      {availableUserIds.map((userId) =>
        users[userId]?.name ? (
          <Typography variant="h3">{users[userId].name}</Typography>
        ) : (
          <LoadingButton
            key={userId}
            loading={users[userId]?.isLoading}
            variant="outlined"
            onClick={() => loadUser(userId)}
          >
            Load User {userId}
          </LoadingButton>
        )
      )}
    </div>
  );
}

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

The problem is that useState's setter is asynchronous, so, in your loader function, when you define const updatedUsers = { ...users };, user is not necessary updated.

Luckily, useState's setter provides allows us to access to the previous state. If you refactor your code like this, it should work:

  const loadUser = (userId) => {
    // Mark button as loading
    const updatedUsers = { ...users };
    updatedUsers[userId] = {
      id: userId,
      name: undefined,
      isLoading: true,
      isFailed: false
    };
    setUsers(updatedUsers);

    // Call API
    getUsersApi(userId).then((userName) => {
      // Update state with user name
      
    setUsers(prevUsers => {
        const updatedUsers = { ...prevUsers };
      updatedUsers[userId] = {
        ...updatedUsers[userId],
        name: userName,
        isLoading: false,
        isFailed: false
      };
      return updatedUsers
      });
    });
  };

Here a React playground with a simplified working version.

about 4 years ago · Juan Pablo Isaza 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!