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!
2 Replies
Unknown User
Unknown User2y ago
Message Not Public
Sign In & Join Server To View
pandeyman
pandeyman2y ago
I didn't wanna disable refetch on window focus, so I checked for the status of the query. If the query is in the "loading" state, I'm not redirecting the user and it works as expected. Thanks for answering the question though!
Want results from more Discord servers?
Add your server