-1

AppRoutes:

return (
    <Routes>
        <Route path="/" element={<Home/>}/>
        {!userStore.isLogin && (
            <>
                <Route path="/profile" element={<Navigate replace to="/auth"/>}/>
                <Route path="/auth" element={<Auth/>}/>
                <Route path="/register" element={<Register/>}/>
            </>
        )}
        {userStore.isLogin && (
            <>
                <Route path="/profile" element={<Profile/>}/>
                <Route path="/auth" element={<Navigate replace to="/"/>}/>
                <Route path="/register" element={<Navigate replace to="/"/>}/>
            </>
        )}
    </Routes>
)

onAuth function

const onAuth = async () => {
    const result = await login(data);
    if (result.ok) {
        const localUser = JSON.stringify({
            token: result.token,
            isLogin: true
        })
        localStorage.setItem("user", localUser)
        dispatch(userLogged({token: result.token}));
        navigate("/profile")
    } else {
        setMessage(result?.message || "Произошла ошибка при выполнении запроса")
    }
}

navigate("/profile") from onAuth function. It doesn't work. From the /auth page, I am redirected to /, via a condition in AppRoutes as if navigate("/profile") is ignored or overwritten

  • Seems the issue is that the dispatched `userLogged` action is processed by Redux *after* the `navigate("/profile")` call which occurs immediately, is this the issue? Are you just trying to implement [route protection](/a/66289280/8690857)? Can you edit your post to include a [mcve] for all the relevant code you are using? What is `userStore` in the first snippet, and where is `onAuth` used/called in the second snippet? – Drew Reese Jul 30 '22 at 07:32

1 Answers1

0

I changed the routing and it started working correctly

return (
    <Routes>
        {isLogin ? (
            <>
                <Route path="/profile" element={<Profile/>}/>
            </>
        ) : (
            <>
                <Route path="/auth" element={<Auth/>}/>
                <Route path="/register" element={<Register/>}/>
            </>
        )}
        <Route path="*" element={<Home/>}/>
    </Routes>
)