reactjs - 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>
);
};
解决方案
推荐阅读
- sql-server - 有没有办法在临时表上保留生成的 ID
- regex - Avoid negative lookahead regex in mail spam detection
- python - 用于获取社交数据的加密货币 API
- django - 具有来自其他模型类的多个对象的 Django 模型类
- javascript - 为什么我的应用程序在使用 node 启动但不使用 nodemon 时返回 304 状态代码
- java - 如何通过 JDBC 连接器从我的本地 Java 应用程序连接到 AWS RDS
- r - 邻接矩阵不对称的错误
- c++ - 如何使用 OpenGL 渲染平滑字体(实际上是任何“扁平”形状)?
- angular - Angular 11 ngx-translate 不适用于 app.component 以外的其他组件
- jenkins - Jenkins 中 Bamboo 环境的替代方案是什么?