0

See here's my protected route component code in which I get data from the redux store. ProtectedRoute.js and here the app.js code and when I open the react app redux store it has these values redux store values that means isAuthenticated is true, so according to the code it has to be redirected to '/profile' route but when I write the http://localhost:3000/profile manually (like this browser's search bar) to the browser's search bar it redirected to the '/' route despite of the fact that user is authenticated and it should renders the '/profile' page's component and in the browser's console it shows browser's console that means isAuthenticated is false in ProtectedRoute but when the app.js renders I made dispatch which ensures that isAuthenticated should set to true according to the condition applied. I understand how to write protected route and I wrote it but this issue is occurring in my code my you please answer to my this particular code. I think logically my code correct but it's output is not .

here's the code of App.js in which every thing should render first before any component renders

import { useEffect } from 'react';
import 'remixicon/fonts/remixicon.css'
import {Routes,Route} from 'react-router-dom';
import Register from './components/Auth/Register';
import Hero from './components/Home/Hero';
import {useSelector,useDispatch} from 'react-redux';
import {getProductsAsync} from './asyncActions/productAction';
import { getUserDataAsync } from './asyncActions/userAction';
import CartPage from './components/Home/CartPage';
import OrderPage from './components/Home/OrderPage';
import { transitions, positions, Provider as AlertProvider } from 'react-alert'
import AlertTemplate from 'react-alert-template-mui'
import { createTheme, ThemeProvider} from '@mui/material/styles';

import NavBar from './components/NavBar/NavBar';

import HomeLayout from './components/Elements/MainElements/HomeLayout';
import ProductCard from './components/Elements/MainElements/ProductCard';
import HomeElements from './components/Elements/MainElements/HomeElements';
import AboutPage from './components/Home/AboutPage';
import BrowsePage from './components/Home/BrowsePage';
import TrendingPage from './components/Home/TrendingPage';
import UserOrders from './components/Elements/UserOrders/UserOrders';
import ProfilePage from './components/Profile/ProfilePage';
import WishList from './components/Elements/WishList/WishList';
import Dashboard from './components/Dashboard/Dashboard';

import ProtectedRoute from './components/utils/ProtectedRoute';

import {store} from './store';




function App() {
  const {products,loading}=useSelector((store)=>store.products);
  const {user,isAuthenticated,admin}=useSelector((store)=>store.user);
  const {theme}=useSelector((store)=>store.themeControl);
  const MUItheme = createTheme({
    palette: {
      primary: {
        main: '#E26849',
      },
      secondary:{
        main:'#669C96'
      },
      mode:`${theme?'light':'dark'}`
    },
  });

  const dispatch=useDispatch();
  const options = {
    // you can also just use 'bottom center'
    position: positions.BOTTOM,
    timeout: 1000,
    offset: '30px',
    // you can also just use 'scale'
    transition: transitions.SCALE
  }


 
  useEffect((e)=>{
  //  dispatch(getUserDataAsync());
   store.dispatch(getUserDataAsync());
  //  dispatch(getProductsAsync());

  },[])
  return (
    <div className="App">
        <ThemeProvider theme={MUItheme}>
        <AlertProvider template={AlertTemplate} {...options}>
        <Routes>
        <Route exact path='/' element={<Hero></Hero>}>
             <Route index element={ <HomeLayout heading={`${(user)?`${user.username}!`:" "} have a good day`}
                                                   cardData={!loading && products.map((elm)=><ProductCard key={elm._id} data={elm}/>)}
                                                   boxStyle={"grid"}
                                                   rightSide={<HomeElements/>}/>}/>
             <Route path="cart" element={<CartPage/>}/>
             <Route path="browse" element={<BrowsePage/>}/>
             <Route path="trending" element={<TrendingPage/>}/>
             <Route path="about" element={<AboutPage/>}/>
             <Route path="profile" 
                   element={<ProtectedRoute>
                    <ProfilePage/>
                    </ProtectedRoute>}/>
             <Route path="myOrders" element={<ProtectedRoute><UserOrders/></ProtectedRoute>}/>
             <Route path="wishlist" element={<WishList/>}/>

            

        </Route>
        <Route exact path="/order" element={<OrderPage></OrderPage>}/>
        <Route exact path="/auth" element={<Register/>}/>
        <Route exact path="/dashboard" element={<ProtectedRoute>
          <Dashboard/>
          </ProtectedRoute>}/>
       
        </Routes>
        </AlertProvider>
        </ThemeProvider>

     
   
      {/* <button onClick={()=>{ dispatch(getProductsAsync());}}>clickME</button> */}
    </div>
  );
}

export default App;

I don't know How to fix this issue? Please Help me!

moulsiri
  • 1
  • 2
  • Basic gist is that the protected route component is likely using initial redux state value and redirecting prior to the store being updated, so update the store to ***not*** use an initial value matching either authenticated or unauthenticated state values, and add an additional check for this non-settled auth status to render something other than the routed content or redirect. You might also consider adding `redux-persist` to your project so it can persist your store to localStorage, and more importantly, rehydrate your store ***prior*** the the app loading so the auth state is available. – Drew Reese Sep 25 '22 at 16:25
  • Part of the issue is with *how* you have implemented the protected route. If you really feel this isn't a duplicate and the above comment doesn't help then please edit the post to include a [mcve] for all the relevant code you are working with and have an issue using. The redux state setup, the router and routes, the protected route component, etc. – Drew Reese Sep 25 '22 at 16:36
  • I got it! but I don't able to understand where to add that additional check or How to rehydrate the store prior the app loading. – moulsiri Sep 25 '22 at 16:37
  • The code examples in this [answer](/a/66289280/8690857) show where the check should be located. Basically anywhere prior to the main return. If you want to use redux-persist also persist/rehydrate the store then follow the instructions from [quick start](https://github.com/rt2zz/redux-persist#quickstart) guide. – Drew Reese Sep 25 '22 at 16:41

0 Answers0