Search code examples
javascriptreactjspromiseclosures

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


Solution

  • 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.