【问题标题】:How to wait for auth state to load on the client before fetching data如何在获取数据之前等待身份验证状态加载到客户端
【发布时间】:2020-11-07 01:37:09
【问题描述】:

最近我偶然发现了 useAuth 和 useRequireAuth 钩子:https://usehooks.com/useRequireAuth/。当涉及到客户端身份验证时,它们非常有用。但是,等待身份验证数据可用以获取其他数据的正确方法是什么?我想出了以下代码:

const Page = () => {
// makes sure user is authenticated but asynchronously, redirects if not authenticated, short screen-flash
useRequireAuth()

// actual user object in state, will be updated when firebase auth state changes
const user = useStoreState((state) => state.user.user);


if (!user) {
  return <div>Loading</div>
}


useEffect(() => {
if (user) {
  fetchSomeDataThatNeedsAuth();
}
}, [user]);


return (
    <h1>Username is: {user.name}</h1>
)

}

这是一种“好”的方法还是可以通过某种方式改进?感觉非常冗长,需要为每个需要身份验证的组件重复。

【问题讨论】:

    标签: reactjs react-hooks next.js


    【解决方案1】:

    这对我来说很好。您可以改进的是您的 useRequireAuth() 可以返回用户,但这取决于您。

    此外,您可能应该在呈现 user.name 之前检查用户是否已定义。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-01-25
      • 1970-01-01
      • 1970-01-01
      • 2014-04-23
      • 2023-03-08
      • 2016-08-11
      相关资源
      最近更新 更多