TanStackT
TanStack17mo ago
1 reply
urgent-maroon

Wont navigate away me after successfull sign in

i am using protected rotues with context but my problem is after i sign in state change to true but wont navigate me to page.
function App() {
    const auth = useAuth();
    if (auth.isLoading) {
        return null;
    } else {
        return <RouterProvider router={routerConfig} context={{ auth }} />;
    }
}

import { useGetMe } from '@/api/endpoints/authApi';
import { createContext, ReactNode, useContext } from 'react';
import { User } from '@/interfaces/user';

export interface AuthContextType {
    user: Pick<User, 'id' | 'fullname' | 'isAdmin'> | null;
    isLoading: boolean;
    authenticated: boolean;
}

interface AuthContextProps {
    children: ReactNode;
}

const AuthContext = createContext<AuthContextType>({
    user: null,
    isLoading: true,
    authenticated: false,
});

export const AuthContextProvider = ({ children }: AuthContextProps) => {
    const { data: user, isLoading } = useGetMe();

    return (
        <AuthContext.Provider
            value={{
                user: user || null,
                isLoading,
                authenticated: !!user,
            }}
        >
            {children}
        </AuthContext.Provider>
    );
};

export const useAuth = () => {
    return useContext(AuthContext);
};
import { AuthContextType } from '@/context/authContext';
import MainLayout from '@/layouts/mainLayout';
import { createRootRouteWithContext } from '@tanstack/react-router';

type RouterContext = {
    auth: AuthContextType;
};

export const Route = createRootRouteWithContext<RouterContext>()({
    component: () => <MainLayout />,
});

import AllVideos from '@/pages/allVideos';
import { createFileRoute, redirect } from '@tanstack/react-router';

export const Route = createFileRoute('/videos/')({
    beforeLoad: ({ context }) => {
        const { authenticated } = context.auth;
        if (!authenticated) {
            throw redirect({ to: '/' });
        }
    },
    component: () => <AllVideos />,
});
image.png
Was this page helpful?