N
N
Nikita2019-05-05 19:10:20
React
Nikita, 2019-05-05 19:10:20

How to save React user session?

Good afternoon, how can I save the user session, namely the login state on React?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Anton Spirin, 2019-05-05
@0x452

What can be recommended here.
When logging in, store the token in the cookie and application storage.
If you use axios, then you can store the token in the default headers.
Example using redux, js-cookie and axios:

cookie.set('token', token);
dispatch(setToken(token)); // если не используете Redux, тут будет this.setState
axios.defaults.headers.common.Authorization = `Bearer ${token}`;

During initialization, check for the presence of a token:
const token = cookie.get('token');

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

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

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question