Skip to content

Commit

Permalink
Merge pull request #2399 from Agenta-AI/fix(frontend)/route-race-cond…
Browse files Browse the repository at this point in the history
…ition-after-new-account-creation-in-cloud

[Fix] Prevent redirection from ProtectedRoute component if there's another route change is already happening
  • Loading branch information
mmabrouk authored Jan 24, 2025
2 parents 9eed012 + d284e40 commit 69bbb6e
Showing 1 changed file with 16 additions and 2 deletions.
18 changes: 16 additions & 2 deletions agenta-web/src/components/ProtectedRoute/ProtectedRoute.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import {useSession} from "@/hooks/useSession"
import {useRouter} from "next/router"
import React, {PropsWithChildren, useEffect, useState} from "react"
import React, {PropsWithChildren, useEffect, useRef, useState} from "react"
import {useProjectData} from "@/contexts/project.context"

const ProtectedRoute: React.FC<PropsWithChildren> = ({children}) => {
Expand All @@ -9,8 +9,22 @@ const ProtectedRoute: React.FC<PropsWithChildren> = ({children}) => {
const {pathname} = router
const [shouldRender, setShouldRender] = useState(false)
const {isLoading, isProjectId} = useProjectData()
const isBusy = useRef(false)

useEffect(() => {
const startHandler = (_newRoute: string) => (isBusy.current = true)
const endHandler = (_newRoute: string) => (isBusy.current = false)

router.events.on("routeChangeStart", startHandler)
router.events.on("routeChangeComplete", endHandler)
return () => {
router.events.off("routeChangeStart", startHandler)
router.events.off("routeChangeComplete", endHandler)
}
}, [router])

useEffect(() => {
if (isBusy.current) return
if (loading || isLoading) {
setShouldRender(false)
} else {
Expand All @@ -30,7 +44,7 @@ const ProtectedRoute: React.FC<PropsWithChildren> = ({children}) => {
setShouldRender(!!isProjectId)
}
}
}, [pathname, isSignedIn, loading, isProjectId, isLoading])
}, [pathname, isSignedIn, loading, isProjectId, isLoading, router])

return <>{shouldRender ? children : null}</>
}
Expand Down

0 comments on commit 69bbb6e

Please sign in to comment.