Search code examples
javascriptreactjsreduxreact-hooksreact-router-dom

How can I force the user to go to Login before going to other component?


How can I make the admin go to login first before going to other components? So I've been getting an error about

TypeError: Cannot read properties of null (reading 'isAdmin')

I know where this came from, it's from my

const admin = useSelector((state) => state.user.currentUser.isAdmin)

I was thinking that forcing the admin to redirect to other page, but when I try to use ternary operator, the program itself already calls the useSelector.

Is there any way I can approach this problem?

import { useSelector } from 'react-redux'
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom'
import './App.css'
// import Sidebar from './components/sidemenu/Sidebar'
import Home from './pages/home/Home'
import Login from './pages/login/Login'
// import NewProduct from './pages/newProduct/NewProduct'
// import NewUser from './pages/newUser/NewUser'
// import ProductList from './pages/product/ProductList'
// import Product from './pages/productItem/Product'
// import User from './pages/user/User'
// import UserList from './pages/userList/UserList'
function App() {
  const admin = useSelector((state) => state.user.currentUser.isAdmin)
  // const admin = false
  return (
    <Router>
      <Switch>
        <Route path="/">{admin ? <Home /> : <Login />}</Route>
      </Switch>
    </Router>
  )
}

export default App

Solution

  • You should make your code safe.

    For modern js you could use the optional chaining operator

    const admin = useSelector((state) => state.user?.currentUser?.isAdmin)
    

    A more traditional approach to do the same thing

    const admin = useSelector((state) => state.user && state.user.currentUser && state.user.currentUser.isAdmin)