How to use Redirect in my React application

Asked

Viewed 12 times

-1

I’m making an application in React, I’m using the Redux and the saga Redux. I am protecting the routes, but when I do the redirect does not take me to the main page of my appeal. That’s the code of my protectedRoute:

import React from "react";
import { Redirect, Route } from "react-router-dom";

function ProtectedRoute({ component: Component, ...restOfProps }) {
    const isAuthenticated = localStorage.getItem("isAuthenticated");
    console.log("Aqui")
    return (
        <Route
        {...restOfProps}
        render={(props) =>
            isAuthenticated ? <Component {...props} /> : <Redirect push to="/login" />
        }
        />
    );
}

export default ProtectedRoute;

And my route file is like this:

import React from 'react'
import { Route, BrowserRouter, Switch } from "react-router-dom";
import Login from '../components/Login/index'
import Event from '../components/Event/index'
import Schedule from '../components/Schedule/index'
import ProtectedRoute from './protectedRoute';

const Routes = () => {
    return(
        <BrowserRouter>
            <Switch>
                <Route path="/login" component={Login}/>
                <ProtectedRoute exact path="/" component={Event}/>
                <ProtectedRoute path="/schedule" component={Schedule} />
            </Switch>
        </BrowserRouter>
    )
}

export default Routes;

In my sagas I make the request for my API and and save the token in the Storage location:

import {all, call, fork, put, takeEvery, select} from "redux-saga/effects";
import axios from 'axios'
import {
    CLICK_BUTTON_LOGIN,
} from '../actions/actionTypes'
import { updateSuccess } from "../actions/login";

const verifyLoginInAPI = async(email,password) =>{
    return await axios.post("http://localhost:4000/user/login",{
        email: email,
        password: password
    })
    .then(response => response)
    .catch(error => error)
}

function* confirmDataLogin(){
    try{
        const email = yield select(state => state.login.email)
        const password = yield select(state => state.login.password)
        const result = yield call(() => verifyLoginInAPI(email, password))
        if(result.status === 200){
            localStorage.setItem("isAuthenticated",result.data.token)
        }
    }catch(e){
        yield call(() => console.error('ERRO: ', e))
    }
}

export function* confirmDataLoginSaga(){
    yield takeEvery(CLICK_BUTTON_LOGIN, confirmDataLogin)
}

I need help to: once the user logs in, they are redirected to the main page.

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.