pandeyman
pandeyman
TTCTheo's Typesafe Cult
Created by pandeyman on 2/7/2023 in #questions
Proper way to handle a protected route with react-query
Greetings all, I need to protect a specific page and show it users only if they have a certain "status" which is fetched through a simple query to the server. See this code example for reference:
import React from "react";
import { api } from "../utils/api";

const Page = () => {
const { data: userStatus, isLoading } = api.example.status.useQuery();

useEffect(() => {
if(userStatus?.status !== "accepted"){
router.push("/setup")
}
}, [userStatus?.status]);

if(isLoading) {
return <div>Loading...</div>
}

if(userStatus) {
return <h1>Welcome</h1>
}

}
import React from "react";
import { api } from "../utils/api";

const Page = () => {
const { data: userStatus, isLoading } = api.example.status.useQuery();

useEffect(() => {
if(userStatus?.status !== "accepted"){
router.push("/setup")
}
}, [userStatus?.status]);

if(isLoading) {
return <div>Loading...</div>
}

if(userStatus) {
return <h1>Welcome</h1>
}

}
The above example works perfectly well, the only problem is that if the user leaves the page for too long and switch tabs, when they come back to the site, they are redirected to the "/setup" page. I'm confused as to what could be the optimal way of handling such protected routes. Thank you, any help would be appreciated!
3 replies