Creating a reusable “Token Manager” class in react-native.

Creating a reusable “Token Manager” class in react-native.
Photo by Maxim Zhgulev on Unsplash

In any app, especially an app that has user accounts, it is a very common task to check for existing user token and redirects the user either to AuthStack or AppStack according to the token found. So for this common task, we can create our own token manager class which handles the common functionalities related to user token. In today’s code read I will try to document that.

Usually, we store tokens locally in our AsyncStorage, so we have 2 functions in our class. One is to set and the other one is to clear the token.

Now the next one is the most important function, anywhere in our app where we want to get the valid token for the user we need to check a few things. They are the following:

  • First, we check if there is any saved token in our local storage. We check for the tokenObj, that object should have the necessary information about the token. Like token value, expires-at, etc.
  • If there is not an existing token, we return null.
  • If there is an existing token, we need to check if the token is still valid, meaning if it is still not expired. This information should be passed from API when the user logged in or signed up in the app before.

So with all these steps our function should look like following

Finally we have our new token function where if the token is expired we request for refresh token from the API.

Once we have this class set up, we just need to import this class and create an object to get a valid token from anywhere in our app like folllowing.

The full code for the tokenizer class is given below for reference.


Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *