A
A
Arthur2020-01-30 11:23:16
React
Arthur, 2020-01-30 11:23:16

Where and how to handle non-ui logic in spa?

stack

  • react
  • redux
  • redux-saga


Case.
The authorization token lives for 10 minutes.
The user is authorized in the system. Shows some activity, but does not send requests. It logs out because the token becomes obsolete.

Invented solution. I track user activity (for example, mouse movement), launch an interval in which at 10 minutes I check if there were mouse movements and send a background request to renew the token.

Question . What is the correct way to implement this in my stack? Exactly how to compose?

The current solution looks like this, but I clearly understand that it needs to be done somehow in the flow sag

export class Tracker {
  constructor({trackEvents, dropActivityTimeMs}) {
    this.dropActivityTimeMs = dropActivityTimeMs;
    this.trackEvents = trackEvents;
    this.wasActivity = false;
    this.dropActivityIntervalId = null;
  }

  restartDropActivity() {
    clearInterval(this.dropActivityIntervalId);
    console.log('Обнуление активности перезапущено');
    this.dropActivityIntervalId = setInterval(() => {
      this.wasActivity = false;
    }, this.dropActivityTimeMs);
  }

  init() {
    this.trackEvents.forEach(event => {
      document.addEventListener(event, () => {
        console.log(`Было событие ${event}`);
        this.wasActivity = true;
        this.restartDropActivity();
      });
    })
  }
}


//в корне приложения вызываю
const events = ['mousemove'];
const tracker = new Tracker({
  trackEvents: events,
  dropActivityTimeMs: 5000,
});
const prolongateAfterMs = 3000;
tracker.init();
 
setInterval(() => {
  console.log(`активность в последние ${tracker.dropActivityTimeMs}ms`, tracker.wasActivity);
  if (tracker.wasActivity) {
    api.updateToken();
  }
}, prolongateAfterMs);

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vladyslav Kliuiev, 2020-01-31
@TrueBlackBox

I can't answer more on the phone, and I don't quite see the whole situation, but why not assign the time of the token when the page is closed? That is, when we open, we log in, sit at least until old age, and for example, in componentWillUnmount, or something similar, when the page is closed, we tell the token that it has 10 minutes left to live. Of course, I have not yet encountered such a task, but still it looks better than watching the mouse. For when the mouse moves, a lot, VERY many actions are performed, and I'm afraid that at best it will consume a huge amount of resources, and at worst it can even put an open page.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question