'React Router Outlet and Protected Outlet does not working

I want to render outlets based on user login state. The problem is the oulet never get rendered. Only parent element is rendered.I tried using "/:username/boards/*" for path. But that didn't work either.

App.js

<Route element={<ProtectedOutlet />}>
   <Route path="/:username/boards" element={<UserHome logOut={actions.logOut} getAllBoards={actions.getAllBoards} />} >
      <Route path="b" element={<Board />} />
   </Route>
</Route>

ProtectedOutlet.js

import React from "react";
import { Navigate, Outlet } from "react-router-dom";
import { useSelector } from "react-redux";

const ProtectedOutlet = () => {

  const isLoggedIn = useSelector(state => state.auth.isLoggedIn);

return isLoggedIn ? <Outlet /> : <Navigate to="/login" />;
}

export default ProtectedOutlet;

UserHome.js

const UserHome = (props) => {
return (
    <div className="user-home">
        <Navbar />
        <Outlet />
    </div>
)
}


Solution 1:[1]

Problem solved. I changed my codes in ProtectedOutlet

from

const ProtectedOutlet = () => {

const isLoggedIn = useSelector(state => state.auth.isLoggedIn);

return isLoggedIn ? <Outlet /> : <Navigate to="/login" />;
}

to

const ProtectedOutlet = () => {

const { isLoggedIn, user } = useSelector(state => state.auth);

if (!isLoggedIn && !user) return <h1>Loading</h1>

return isLoggedIn ? <Outlet /> : <Navigate to="/login" />;
}

And I've other route for unauthenticated routes like (/login,/register, etc..) called PublicOutlet.js.

PublicOutlet.js

import React from "react";
import { Navigate, Outlet } from "react-router-dom";
import { useSelector } from "react-redux";

const PublicOutlet = () => {

const { isLoggedIn, user } = useSelector(state => state.auth);

return isLoggedIn ? <Navigate to={`/${user.username}/boards`} 
replace={true} /> : <Outlet />;
}

export default PublicOutlet;

The problem is when I enter url in url bar, the protectedoutlet component check if the user is logged in or not. When it is rendered the first time, isLoggedIn state is not updated yet. so it get navigated to /login route. Then /login route is wrapped in publicoutlet component. When publicoutlet component check if the user is is logged in, isLoggedIn state changed to true. So, it get redirected to /${user.username}/boards. It took me 2days to find out the problem. LOL

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Hein Min Htun