How to maintain the session of user React?

Good afternoon, how can I save a user session, namely the login state to React?
March 20th 20 at 11:54
1 answer
March 20th 20 at 11:56
Solution
What I can recommend.
When you authorize save the token in a cookie and store of the application.
If you are using axios, you can save the token in the headers by default.
Example using redux, js cookie and axios:
cookie.set('token', token);
dispatch(setToken(token)); // if not using Redux, there will be this.setState
axios.defaults.headers.common.Authorization = `Bearer ${token}`;


Initialization check for the token:
const token = cookie.get('token');

if (token) {
dispatch(setToken(token));
 axios.defaults.headers.common.Authorization = `Bearer ${token}`;
 // other actions
}


When logout delete the token:
dispatch(deleteToken());
cookie.erase('token');
delete axios.defaults.headers.common.Authorization;

Find more questions by tags React