首页 > 解决方案 > React useState not being set correctly in Context/Provider when resolving a promise

问题描述

I can't seem to figure out the issue as everything reads perfectly but I have commented on the parts that do not seem to fit my intuition on how the hooks are working.

TL;DR, even though I am setting the state (that I have from useState hook) inside the .then() function, it is not actually updating the state but rather keeps the default value I initially assigned.

export function Provider({ children }: Props) {
 const defaultAuthState: UAuthState = {
   isAuthenticated: false,
   user: undefined,
 };
 const [authState, setAuthState] = useState(defaultAuthState);

 ...

 const login = (loginInput: LoginInput): void => {
    const user = UserService.login(loginInput)
      .then((loggedInUser) => {
        const loggedInAuthState = {
          isAuthenticated: true,
          user: loggedInUser,
        };
        /* debugger show that loggedInUser is an actual object here */
        setAuthState(loggedInAuthState);
        /* authState still seems to be in the default state (defaultAuthState) */
        /* this is also reflected when I consume the provider */
      })
      .catch((err) => {
        alert(`${err}`);
      });
  };

  ...

  const contextValue = {
    authState,
    login
  };
  return (
    <AuthContext.Provider value={contextValue}>{children}</AuthContext.Provider>
  );
};

标签: reactjsreact-hooks

解决方案


推荐阅读