T
TanStack16mo ago
stormy-gold

Problems with beforeLoad() and load()

Hello guys, im making my app with react, vite and tanstackrouter, and ive been doing great since i faced this problem from couple weeks whiout a progress and wondering if someone can give me a hand. The problem its releated with how the app its handling the auth of the user, im trying to protect the routes with beforeLoad() but its been ignoring by load() and its rendering first the data. Im trying all the ways to fix it but nothing fix it. If somebody can give me an advice that will be helpful thanks
No description
No description
No description
No description
No description
13 Replies
like-gold
like-gold16mo ago
can you also show the getAllUrls function?
stormy-gold
stormy-goldOP16mo ago
Yes
stormy-gold
stormy-goldOP16mo ago
GitHub
GitHub - starks97/urlShortener: frontend of url shortener
frontend of url shortener. Contribute to starks97/urlShortener development by creating an account on GitHub.
stormy-gold
stormy-goldOP16mo ago
GitHub
GitHub - starks97/urlShortener: frontend of url shortener
frontend of url shortener. Contribute to starks97/urlShortener development by creating an account on GitHub.
stormy-gold
stormy-goldOP16mo ago
If you know something let me know I just want to finish this project
like-gold
like-gold16mo ago
The repo you gave only contains a readme file
stormy-gold
stormy-goldOP16mo ago
Change to master Change to master branch
like-gold
like-gold16mo ago
oh, ok
stormy-gold
stormy-goldOP16mo ago
But yeah I’m having that issue, I can not finish with my app, I’m trying to do my best but I’ve been stuck It supposed to work first the before load
like-gold
like-gold16mo ago
have you tried console logging the data from /session_status? Also, I am sorry but I cannot really look at the entire code right now, if nobody else answers I will try to reply tomorrow
stormy-gold
stormy-goldOP16mo ago
Thanks but I don’t know Should catch before
extended-yellow
extended-yellow16mo ago
the git repo does not contain the _authed route please strip this example down so it is complete but minimal
stormy-gold
stormy-goldOP16mo ago
Yes I didn’t upload that to my git, but it’s the same still loading first loader and then beforeload still ignored i fixed
const test = test();
const test = test();
export interface AuthContextType {
isAuthenticated: boolean;
checkSessionStatus: () => Promise<void>;
}

export const AuthContext = createContext<AuthContextType | null>(null);

export function AuthContextProvider({
children,
}: {
children: React.ReactNode;
}) {
const [isAuthenticated, setIsAuthenticated] = useState<boolean>(false);
const checkSessionStatus = async () => {
//this is important to prevent infinite loop and making unnecessary requests, this is like cache for the session status.
if (isAuthenticated) return;

try {
const response = await fetch(`${baseUrl}/session_status`, {
method: "GET",
headers: {
"Content-Type": "application/json",
},
credentials: "include",
});

const data = (await response.json()) as {
status: "access" | "refresh" | "login";
};

if (response.status === 401 || data.status === "login") {
setIsAuthenticated(false);
window.location.href = "/auth/login";
} else if (data.status === "refresh") {
setIsAuthenticated(false);
window.location.href = "/auth/refresh";
}

setIsAuthenticated(true);
} catch (error) {
setIsAuthenticated(false);
throw error;
}
};

return (
<AuthContext.Provider value={{ isAuthenticated, checkSessionStatus }}>
{children}
</AuthContext.Provider>
);
}
export function useAuth() {
const context = React.useContext(AuthContext);

if (!context) {
throw new Error("useAuth must be used within an AuthProvider");
}

return context;
};
export interface AuthContextType {
isAuthenticated: boolean;
checkSessionStatus: () => Promise<void>;
}

export const AuthContext = createContext<AuthContextType | null>(null);

export function AuthContextProvider({
children,
}: {
children: React.ReactNode;
}) {
const [isAuthenticated, setIsAuthenticated] = useState<boolean>(false);
const checkSessionStatus = async () => {
//this is important to prevent infinite loop and making unnecessary requests, this is like cache for the session status.
if (isAuthenticated) return;

try {
const response = await fetch(`${baseUrl}/session_status`, {
method: "GET",
headers: {
"Content-Type": "application/json",
},
credentials: "include",
});

const data = (await response.json()) as {
status: "access" | "refresh" | "login";
};

if (response.status === 401 || data.status === "login") {
setIsAuthenticated(false);
window.location.href = "/auth/login";
} else if (data.status === "refresh") {
setIsAuthenticated(false);
window.location.href = "/auth/refresh";
}

setIsAuthenticated(true);
} catch (error) {
setIsAuthenticated(false);
throw error;
}
};

return (
<AuthContext.Provider value={{ isAuthenticated, checkSessionStatus }}>
{children}
</AuthContext.Provider>
);
}
export function useAuth() {
const context = React.useContext(AuthContext);

if (!context) {
throw new Error("useAuth must be used within an AuthProvider");
}

return context;
};
const queryClient = new QueryClient();

const router = createRouter({
routeTree,
context: {
queryClient,
auth: null as AuthContextType | null,
},
defaultPreload: "intent",
defaultPreloadStaleTime: 0,
});

// Register things for typesafety
declare module "@tanstack/react-router" {
interface Register {
router: typeof router;
}
}
function InnerApp() {
const auth = useAuth();
return <RouterProvider router={router} context={{ auth }} />;
}
function App() {
return (
<QueryClientProvider client={queryClient}>
<AuthContextProvider>
<InnerApp />
</AuthContextProvider>
</QueryClientProvider>
);
}
const rootElement = document.getElementById("app")!;

if (!rootElement.innerHTML) {
const root = ReactDOM.createRoot(rootElement);
root.render(<App />);
}
const queryClient = new QueryClient();

const router = createRouter({
routeTree,
context: {
queryClient,
auth: null as AuthContextType | null,
},
defaultPreload: "intent",
defaultPreloadStaleTime: 0,
});

// Register things for typesafety
declare module "@tanstack/react-router" {
interface Register {
router: typeof router;
}
}
function InnerApp() {
const auth = useAuth();
return <RouterProvider router={router} context={{ auth }} />;
}
function App() {
return (
<QueryClientProvider client={queryClient}>
<AuthContextProvider>
<InnerApp />
</AuthContextProvider>
</QueryClientProvider>
);
}
const rootElement = document.getElementById("app")!;

if (!rootElement.innerHTML) {
const root = ReactDOM.createRoot(rootElement);
root.render(<App />);
}
export const Route = createFileRoute("/_authed")({
beforeLoad: async ({ context }) => {
const { checkSessionStatus, isAuthenticated } = context.auth;
if (!isAuthenticated) {
try {
await checkSessionStatus();
} catch (error) {
console.error("Error checking session status", error);
window.location.href = "/auth/login";
}
}
},

errorComponent: () => {
return <div>There was an error loading the route</div>;
},
});
export const Route = createFileRoute("/_authed")({
beforeLoad: async ({ context }) => {
const { checkSessionStatus, isAuthenticated } = context.auth;
if (!isAuthenticated) {
try {
await checkSessionStatus();
} catch (error) {
console.error("Error checking session status", error);
window.location.href = "/auth/login";
}
}
},

errorComponent: () => {
return <div>There was an error loading the route</div>;
},
});
if somebody wants to know how i made it, well it wasnt easy to realize, but at the same time easy

Did you find this page helpful?