A
A
Alex Ozerov2021-12-04 16:38:53
typescript
Alex Ozerov, 2021-12-04 16:38:53

How to make a correct redirect in react router dom 6?

I'm trying to redirect after user authorization, but I'm catching a stack count. I'm doing it for the first time in version 6.
61ab6f4c46487521957785.png

import React, {useContext, useState } from 'react';
import {Form, Button} from 'react-bootstrap';
import AppContext from '../../../context/AppContext';
import PanelWrapper from "../../../components/common/PanelWrapper";
import AuthService from "../../../services/AuthService";
import {useNavigate, Navigate, useLocation} from "react-router-dom";
import {ERoles} from "../../../types/enums/ERoles";

type TProps = {
    isReg?: boolean
    role?: ERoles
}

function Auth({isReg, role}: TProps){
    const {language, setCurrentUser, setInitialized, currentUser, initialized} = useContext(AppContext)
    const [login, setLogin] = useState('')
    const [pass, setPass] = useState('')
    const navigate = useNavigate()

    const onFormSubmit = async (event: React.FormEvent<HTMLFormElement>) => {
        event.preventDefault()
        try{
            const response = await AuthService.login(login as string, pass as string)
            
            if(response.data.accessToken !== undefined){
                localStorage.setItem('token', response.data.accessToken)
                setCurrentUser(response.data.user)
                setInitialized(true)
                console.log(currentUser)
            }
        }
        catch(err){
            console.log(err)
        }
    }
    return initialized ?
        <Navigate to={AuthService.redirectByRole(role)} replace /> 
        :
        (
           <div>Here was a very long code for auth</div>
        );
}

export default Auth;

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question