Weird cookies behaviour in a ReactJS application

Viewed 332

Currently, I'm working on a classified ads website where I'm using ReactJS on the front-end. Unfortunately, right now I have some troubles with cookies behaviour so I'm trying to find where the issue is, but no luck for many days. The problem is, I'm using cookies to save user email and user id in cookies to check if it is logged in or out. For some reason, sometimes the page must be refreshed to get user email and id from cookies. The second problem is that after the user is logged out, navigating through pages and refreshing the site, the user is logged in again and I have no idea how this is happening.

Please, check the video to see the bug in action https://youtu.be/Xrhw2Oa9_1k

Link to the repository https://github.com/tourniquet/classified-frontend-react

Also, if there are some good tutorials on how to manage logged user data, please don't hesitate to share them with me. Thank you in advance!

2 Answers

If I understood your question correctly

  • you are trying to logout but once the app refreshes you are logged-in
  • also sometime you need to refresh to get email and id

This is a pretty common issue, underrated I must say, Modern browsers does not really delete the site data until force refreshed/reopened etc etc...

To counter this issue, i will recommend you to keep the same logic to delete the cookies but swap the data structure and conditional logic to check the login activity.

So change your storage from

id = ...
email = ......

to

userData: {
  id: ....,
  email: ......
}

you will have to use JSON.parse while reading the cookie and JSON.stringify to save the data

But this much efforts for what ? what would you gain ?

  • Organised User Information
  • Handing the issue of cookie not getting deleted - by setting the cookie to

    userData: {}

    and then deleting it and while logging-in checking if id and email exist is userData using hasProperty method if Js

  • A controlled user information which can store and process (using a js util you write in react) more attributes (maybe session storage or server validation etc etc)

  • Encrypting all the user data if you are into that sort of security thing

I hope I gave you an approach to work on and tackle the issue in a systematic way :-)

Also remember to check if the cookie do not exist then to set it blank.

On logout, you are deleting the cookies but not updating the Redux state.
Remove the email and id from redux state.

But the better way is to move this whole cooked management to reducer:

i.e.

  • reducer should set the initial state by examining cookies
  • on LOGIN action, reducer should set the cookies in addition to updating the state
  • on LOGOUT action, reducer should delete the cookies in addition to updating the state

Rest of your code should check logged in status only from redux state.
This way, you will have a single source of truth.

Related