When I use PrivateRoute, I always go to the login page once when I reload the page

Viewed 109

Currently, I use the following PrivateRoute to determine if the user is logged in, and if so, the user is taken to the specified page, and if not, the user is taken to the login page. However, when I reload the page, it momentarily transitions to the login page and then to the root page, and I cannot display the /accounts or /notes page again.

This phenomenon also occurs when you type directly into the address bar.

If you know more about it, I would appreciate it if you could tell me why this kind of decrease is happening.

enter image description here

import React from 'react'
import { Route, Redirect } from 'react-router-dom'
import { connect } from 'react-redux'

const PrivateRoute = ({ component: Component, auth, ...rest }) => (
    <Route
        {...rest}
        render={props => {
            if (auth.isLoading) {
                return <h2>Loading...</h2>;
            } else if (auth.isAuthenticated) {
                return <Component {...props} />;
            } else {
                return <Redirect to='/login' />;
            }
        }}
    />
);

const mapStateToProps = state => ({
    auth: state.auth
})

export default connect(mapStateToProps)(PrivateRoute);

action

export const login = (username, password) => dispatch => {

    const config = {
        headers: {
            'Content-Type': 'application/json',
        }
    };

    const body = JSON.stringify({ username, password });

    axios
        .post(`${url}/api/auth/login`, body, config)
        .then((res) => {
            dispatch({
                type: LOGIN_SUCCESS,
                payload: res.data,
            });
        })
        .catch((err) => {
            dispatch(returnErrors(err.response.data, err.response.status));
            dispatch({
                type: LOGIN_FAIL,
            });
        });
};

1 Answers

The problem is that your auth state in redux will lost each time page reload so you can not identify authentication anymore. To prevent that your can save your state in localStorage or use redux-persist for it.

Related