Afrikaans
Akan
Albanian
Amharic
Arabic
Armenian
Azerbaijani
Basque
Belarusian
Bemba
Bengali
Bihari
Bosnian
Breton
Bulgarian
Cambodian
Catalan
Cebuano
Cherokee
Chichewa
Chinese (Simplified)
Chinese (Traditional)
Corsican
Croatian
Czech
Danish
Dutch
English
Esperanto
Estonian
Ewe
Faroese
Filipino
Finnish
French
Frisian
Ga
Galician
Georgian
German
Greek
Guarani
Gujarati
Haitian Creole
Hausa
Hawaiian
Hebrew
Hindi
Hmong
Hungarian
Icelandic
Igbo
Indonesian
Interlingua
Irish
Italian
Japanese
Javanese
Kannada
Kazakh
Kinyarwanda
Kirundi
Kongo
Korean
Krio (Sierra Leone)
Kurdish
Kurdish (Soranรฎ)
Kyrgyz
Laothian
Latin
Latvian
Lingala
Lithuanian
Lozi
Luganda
Luo
Luxembourgish
Macedonian
Malagasy
Malay
Malayalam
Maltese
Maori
Marathi
Mauritian Creole
Moldavian
Mongolian
Myanmar (Burmese)
Montenegrin
Nepali
Nigerian Pidgin
Northern Sotho
Norwegian
Norwegian (Nynorsk)
Occitan
Oriya
Oromo
Pashto
Polish
Portuguese (Brazil)
Portuguese (Portugal)
Punjabi
Quechua
Romanian
Romansh
Runyakitara
Russian
Samoan
Scots Gaelic
Serbian
Serbo-Croatian
Sesotho
Setswana
Seychellois Creole
Shona
Sindhi
Sinhalese
Slovak
Slovenian
Somali
Spanish
Spanish (Latin American)
Sundanese
Swahili
Swedish
Tajik
Tamil
Tatar
Telugu
Thai
Tigrinya
Tonga
Tshiluba
Tumbuka
Turkish
Turkmen
Twi
Uighur
Ukrainian
Urdu
Uzbek
Vietnamese
Welsh
Wolof
Xhosa
Yiddish
Yoruba
Zulu
So let's now refine this timer approach.
And for example, let's clear it
if the user logged out manually in the meantime.
And to do that, we can use some variable here.
We can add a variable, logoutTimer,
which initially is undefined,
and which is defined outside of all those functions
so that it's a global variable in this file.
And then when we set a timer, like here,
we can store a reference to that timer in that variable,
because setTimeout does return such a reference,
such a identifier, and we can store that
in logoutTimer, in this variable.
And if the logoutHandler is called,
then I wanna check if logoutTimer is set.
And if that's the case, we can call clearTimeout
and pass logoutTimer to it
to clear that timer if a timer was set.
In addition, we wanna store this timer
or this expirationTime now,
so that if we auto logged in the user,
if we retrieved the token from localStorage,
we only use that as an initialToken
if there is a remaining duration for that token.
Because if the user did log in three hours ago,
then that token which was stored, is not worth much anymore.
So what I wanna do here, is I wanna look
into my localStorage and get the token from there
only if the token is valid.
And I wanna delete it, if it's not valid anymore.
For this, I'll add another helper function here,
which you could of course also put into a brand new file,
but I'll manage it here,
which we'll name, retrieveStoredToken.
And here in this function, I wanna get my token,
I wanna get my storedToken,
but I also wanna get my storedExpirationDate.
And for this of course, we need to store it first of all.
So in the loginHandler, when we use that expirationTime
to calculate the duration and set the timer,
I also wanna store it next to my token.
So in localStorage, I'll set our item here
which is the expirationTime or however you wanna name it,
where I store expirationTime.
And important, that now has to be a string,
which it is the way we set it up here.
So now we set that whenever we log in.
Now since we do that, here in retrieveStoredToken,
we can reach out to localStorage
and get that expirationTime, like this.
And now we can check whether we have some remaining time.
So we can get that remainingTime here
by calling calculateRemainingTime
and passing that storedExpirationDate to that function.
And if remainingTime is smaller or equal than zero,
or maybe you even specify some threshold
of let's say, one minute, which would be 3600 milliseconds,
where you say it doesn't make sense to log the user in,
then we wanna not log the user in.
So then I return null here.
We don't retrieve a token.
We also might want to delete that data
in localStorage then.
So we might want to remove our token then
and remove our expirationTime here.
If we make it past this, if check though,
we know that we have a valid token
because there's enough remaining time.
And then I wanna return that storedToken instead.
And I actually don't just wanna return the storedToken,
I also wanna return that remainingTime
so that an appropriate timer can be set.
So I'll return an object here with the token
which is my storedToken and the duration,
or however you wanna name it, which is my remainingTime.
And it's now this retrieveStoredToken function
which we wanna call here in the AuthContextProvider.
The tokenData is then the result
of calling retrieveStoredToken
and tokenData is this object.
And the initialToken therefore is tokenData.token.
However, that will only be available
if we did not return null here.
And therefore of course, I actually wanna check here.
I will set initialToken to a variable
and assign tokenData a token only if
tokenData is truthy.
And it will not be truthy if we return null here.
If it is truthy though, we know that we have a token
and then I'll set my initialToken to that token
which I get from tokenData.
Otherwise, initialToken will stay undefined
and that will then be our initialToken state here.
Now, if we do have tokenData and we do set a token,
then I wanna also set my timer for that.
And I can't do this here now,
because I can't refer to the logoutHandler here,
since it's only defined thereafter.
And therefore I'll do it slightly differently.
I will simply utilize useEffect here.
And then maybe here after the login
and logoutHandler functions were defined,
I'll call useEffect.
And here, my dependency is my tokenData.
So that tokenData which we get here.
And if that changes, which it should only do initially
when this first started,
then I'll check if tokenData is set, if it's truthy.
And if that's the case, then I wanna repeat
that line of code and set my timer here,
and set it to tokenData.duration,
that stands as time in milliseconds.
And that should then set this logoutHandler
to the remaining time here
if we automatically logged in the user.
So it should take that calculated duration
from the storedExpirationTime.
Now to see if that works, I'll console log
tokenData.duration here.
And we should therefore only see that log
if we automatically logged the user in,
and the duration then should also be shorter than one hour.
So if I open my console now
and reload here, and clear this.
If I login here, we don't see a login console,
but if I manually reload, we do see a log.
And that number should be smaller every time I reload.
And it is, because the duration
is shorter and shorter over time.
And since we stored a certain expiration time,
which we can view in the Application tab here
in the DevTools, under Local Storage.
This is the expirationTime that was stored,
and that's the expiration time that makes sense here for me
when I'm recording this, that seems to work.
Now, we can certainly restructure this code
and reconsider this code here,
but that's now generally working the way it should.
We now are able to login and stay logged in
even if we reload it.
And of course, we can also logout
and we automatically log the user out
after a certain duration.
The only remaining thing I wanna do
is that if we do log the user out here
in the logoutHandler, I want to also remove
that expirationTime from localStorage.
But with that, if I now reload,
log back in again, like this,
now if I have a look at my Application tab here,
I got both pieces of data stored here,
and if I logout, it's cleared.
And therefore reloading now doesn't log me in automatically.
But if I try this again and I do log back in again here,
then this is looking good.
And now if I try to visit /auth if I'm logged in,
that doesn't work because of our guard here,
where we deny access to /auth if we are logged in basically.
And with that, that all seems to work the way it should.
Now, one thing I wanna do here now to wrap up this logic
regarding this useEffect call here,
is that for one, we should also add the logoutHandler
as a dependency here, since that is a function
we are defining here in this component function
in which we are using an useEffect,
so we should add that here.
And if we add that function,
we should ensure that this function
is not recreated unnecessarily to prevent infinite loops
or unnecessary effect executions.
And we of course learned how that works,
we can use callback for that.
So, here I will then just quickly import useCallback
from React and wrap logoutHandler with useCallback,
like this, and add my dependency array.
And in here, we actually don't need to add anything,
because localStorage and clearTimeout
are browser built-in functions,
which you don't need to add here,
because they're not specific to your React app
or this component function here
in which you're having this useCallback call.
setToken is a state updating function
which we also don't need to add, we could add it,
but React guarantees us that this function never changes,
so we don't need to add it.
And logoutTimer is a global variable,
which also is outside of that React rendering flow
and therefore also doesn't need to be added here.
So this is how we can define the logoutHandler now.
Can't find what you're looking for?
Get subtitles in any language from opensubtitles.com, and translate them here.