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.
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,
});
});
};
