DEV Community

DEBOS DAS
DEBOS DAS

Posted on

Protected route by token

Get token from authSlice.tsx
import { RootState } from './store';
import { createSlice } from '@reduxjs/toolkit';

type TAuthSate = {
    user: null | object;
    token: null | string;
};

const initialState: TAuthSate = {
    user: null,
    token: null,
};

const authSlice = createSlice({
    name: 'auth',
    initialState,
    reducers: {
        setUser: (state, action) => {
            const { user, token } = action.payload;
            state.user = user;
            state.token = token;
        },
        logout: (state) => {
            state.user = null;
            state.token = null;
        },
    },
});

export const { setUser, logout } = authSlice.actions;

export default authSlice.reducer;

export const userCurrentToken = (state: RootState) => state.auth.token;
export const userCurrentUser = (state: RootState) => state.auth.user;
Enter fullscreen mode Exit fullscreen mode

And this is ProtectedRoute.tsx

`import { ReactNode } from 'react';
import { useAppSelector } from '../../redux/features/hook';
import { userCurrentToken } from '../../redux/features/authSlice';
import { Navigate } from 'react-router-dom';

const ProtectedRote = ({ children }: { children: ReactNode }) => {
    const token = useAppSelector(userCurrentToken);

    if (!token) {
        return <Navigate to="/login" replace={true} />;
    }

    return children;
};
Enter fullscreen mode Exit fullscreen mode

export default ProtectedRote;


**This is router.tsx**

{
        path: '/admin',
        element: (
            <ProtectedRote>
                <App />
            </ProtectedRote>
        ),
        children: routeGenarator(adminPaths),
    },
Enter fullscreen mode Exit fullscreen mode

`

Top comments (0)