1

I have 2 applications 1 website written in nextJs and another one written in React. In the react app the user can log in and based on this action we set a cookie so that the website can take the data of the logged-in user. When the user is logged in in both applications a widget is displayed.

current behavior: When the user logs in to the React application, the widget is set, but in the NextJs application, the widget is displayed after refreshing the page.

expected behavior: When the user logs in or logs out in the React application, I would like to display or not the widget without refreshing the page.

Is that possible? Any suggestion will be appreciated.

mirceaCapa
  • 105
  • 1
  • 6
  • There isnt a cookie onChange event listener per say, but you could do something hacky like for example running an interval every second, comparing 2 cookies (one from 1 second ago and another from right now), then if there is a change, call a set state method in your react component. This is also known as periodic polling and is generally not a good practice but LMK if this helps, cheers. – Dimitar Jul 12 '21 at 14:17
  • Thank you for your answer @DimitarDev . I will try this if I don't find another solution. But there isn't a way to check if a cookie value was changed and based on this to re-render the component? – mirceaCapa Jul 12 '21 at 14:24
  • Do you mind sharing relevant code? – PsyGik Jul 12 '21 at 16:35
  • @juliomalves exactly my approach in the periodic polling option which is probably the simplest solution for solving this. – Dimitar Jul 13 '21 at 14:17
  • @mirceaCapa as I said, there isnt exactly an onCookieChange event listener in JavaScript, which is why you need to create your own artificial "listener" based on a timeout and compared values at different points in time. Imagine the cookie value on the Y axis and the time value on the X axis. Your time delta is basically the timeout you give the setTImeout fn. current Y value = the value of Y at x = current time, last Y value = value of Y at x = current time - deltat time. That is the easiest way to visualize this problem. – Dimitar Jul 13 '21 at 14:21
  • Thanks guys for your time and answers. this solution works for me. https://stackoverflow.com/revisions/63952971/1 – mirceaCapa Jul 16 '21 at 06:42

0 Answers0