Skip to main content

Command Palette

Search for a command to run...

Handle expiration time as number

Updated
1 min readView as Markdown
Handle expiration time as number

Alternative approaches of handling the expiration time.

I'd suggest to use numbers only, instead of a mixture of Date objects, Date strings and numbers. This makes it possible to simplify the code a little.

These two snippets from AuthForm.js and auth-context.js ...

//Authform.js
const expirationTime = new Date(
  new Date().getTime() + +data.expiresIn * 1000
);
authCtx.login(data.idToken, expirationTime.toISOString());


//auth-context.js .
const calculateRemainingTime = (expirationTime) => {
  const currentTime = new Date().getTime();
  const adjExpirationTime = new Date(expirationTime).getTime();
  const remainingDuration = adjExpirationTime - currentTime;
  return remainingDuration;
};

... can be replaced with these two (easy-to-read) lines:

authCtx.login(data.idToken, Date.now() + data.expiresIn * 1000);

const calculateRemainingTime = expirationTime => expirationTime - Date.now();

Please note:

1.

It doesn't matter that we get expiresIn as a string from Firebase, and that localStorage returns strings as well, since with * and - we get an implicit conversion to numbers (in contrast to +).

2.

Date.now() does the same as new Date().getTime(). It's even a little more precise (which is not relevant here), since it captures the time immediately, not only after creating a Date object first.

3.

If we would want to work with an ISOString, we could also write Date.parse(myStr) instead of new Date(myStr).getTime(), without the need of creating a new Date object either.

More from this blog

Omar's blog

135 posts