Next.js Discord

Discord Forum

Redirect user if pathname is empty based on an XHR call

Unanswered
Brown bear posted this in #help-forum
Open in Discord
Brown bearOP
I'm using appDir and when the user navigates to a new page I want to check if the path name is '/' and if it is redirect them to one of our default 'boards'. The catch is that to get the default board I have to make an XHR call. I'm also using SWR. I've tried doing it like this butdefaultBoardRoute comes out as undefined so it redirects to /board/undefined/route/undefined - can anyone point out where I'm going wrong?

I'm doing this in a component some way down the page loading hierarchy, if you think there's a better place for this (I tried in layout.tsx but it would have required me to make it a client side component to make it work which didn't seem right):

export default function Board() {

    const pathname = usePathname()

    const {
        data: defaultBoardRoute,
        error
    } = useSWR<BoardRouteInfoDto>(api('/boardRoutes/default'), fetcher)

    if (!pathname || pathname === '/') {
        redirect(`/board/${defaultBoardRoute?.boardId}/route/${defaultBoardRoute?.routeId}`)
    }
... rest of page

1 Reply

Brown bearOP
I answered my own question here, rather than trying to match pathName in a random component I put this code in my app/page.tsx which of course matches the empty route

I also had to use the router to wait for the SWR call to come back rather than redirect and of course use a client side component

    const router = useRouter()

    const {
        data: defaultBoardRoute,
        error
    } = useSWR<BoardRouteInfoDto>(api('/boardRoutes/default'), fetcher)

    router.push(`/board/${defaultBoardRoute?.boardId}/route/${defaultBoardRoute?.routeId}`)