简体   繁体   English

如何在反应组件中使用firebase保留身份验证状态

[英]How to preserve auth status with firebase in react component

I have a firebase onAuthStateChange and a set of private routes to be rendered with react router v6我有一个火力基础 onAuthStateChange 和一组要使用反应路由器 v6 呈现的私有路由

    useEffect(() => {
    const fetchData = async () =>
      await auth.onAuthStateChanged(async authUser => {
        console.log('here in authuser')
        if (authUser) {
          await dispatch(setUser('SET_USER', authUser))
        } else {
          await dispatch(setUser('SET_USER', null))
        }
      })
    fetchData()
  }, [])

    <Route path='/' element={<PrivateRoute user={users} />}>
            <Route path='/courses/:id' element={<CourseDetails />} />
            <Route
              path='/'
              element={<Courses emailId={users?.user?.email} />}
            />
            <Route path='/enrolled' element={<Enrolled />} />
            <Route path='/authored' element={<Authored />} />
            <Route path='/users' element={<Users />} />
          </Route>

In the protected route component I am checking if user is null then redirect user to login page else render the children.在受保护的路由组件中,我正在检查用户是否为空,然后将用户重定向到登录页面,否则呈现子级。

if (user === null || user.user === null) {
    console.log('Entered!!!!!')
    return <Navigate to='/login' replace />
  } else {
    return children ? children : <Outlet />
  }

On page refresh if I am logged in also I am redirected to login route because onauthstatechange has not finished executing.如果我已登录,则在页面刷新时我也被重定向到登录路由,因为 onauthstatechange 尚未完成执行。 So user is null inside the所以用户在里面是空的

What is the right way to handle this situation and make sure that user gets navigated to the same page where reload happened.处理这种情况并确保用户被导航到发生重新加载的同一页面的正确方法是什么。

You can create a component that handles the check for you.您可以创建一个为您处理检查的组件。

So in your route you wrap your PrivateRoute with your route component like this :因此,在您的路线中,您将PrivateRoute与您的路线组件包装在一起,如下所示:

<Route path='/courses/:id' element={<PrivateRoute><CourseDetails /></PrivateRoute> } />

So what this component does is check if the user is authed .所以这个组件所做的是检查用户是否被authed If it is authed it will render the child component that is your route.如果它被authed ,它将呈现作为您的路由的子组件。 If not it will redirect you to /login如果不是,它会将您重定向到/login

they are talking about it in the docs他们在文档中谈论它

const PrivateRoute =({ children }: { children: JSX.Element }) =>  {
  let auth = useAuth();
  let location = useLocation();

  if (!auth.user) {
    // Redirect them to the /login page, but save the current location they were
    // trying to go to when they were redirected. This allows us to send them
    // along to that page after they login, which is a nicer user experience
    // than dropping them off on the home page.
    return <Navigate to="/login" state={{ from: location }} replace />;
  }

  return children;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM