0

I'm using react js with fetch ,I wanna call an api of refresh token Before my token be expired ,then I calculate the difference between my local date and expire date of the token . I want to call my refresh token api every (expire - localData) - 5 min and update my token in my localStorage. Is that possible ? A call my refresh token in Api.js to work globally ,Is that right ? This is my code but doesn't work like excepting:

Api.js

  const duration = localStorage.getItem("duration")
  useEffect(() =>{
     if(token)
      setInterval(() => {
        RefreshApi.getRefreshToken().then(res => {
          if (typeof res === "string") {
              console.log("Error",res)
          } else {
              var now = moment(new Date(), "DD/MM/YYYY HH:mm:ss");
              var expire = moment(new Date(res.expire), "DD/MM/YYYY HH:mm:ss");
              var diffTime = moment.duration(expire.diff(now));            
              localStorage.setItem("token",res.token);
              localStorage.setItem("expireDuration",diffTime.asMilliseconds());
              localStorage.setItem("expire",res.expire);
          }
      }).catch(err => {
          console.log(err);
      })
      },(duration - 300000))
  },[]) 

refreshApi.js

getRefreshToken: function () {
        return api.get("/refreshToken",{"Authorization": `Bearer ${localStorage.getItem("token")}`}).then(res => {
            if (res.ok) {
                return res.json();
            } else {
                return res.text();
            }
        });
    },

Any help please ?

1 Answer 1

1

You can do this in different ways.

  1. You can use the fetch API provided by JavaScript

SomeJsxFile.jsx

import { getRefreshToken } from './RefreshToken'

  const refreshApi = async () => {
    const token = localStorage.getItem("token");
    
    if(token) {
      const response = await getRefreshToken(token)

      const now = Date.now() // this will return the Epoch time in milliseconds
      const expire = Date.now(response.expire)

      localStorage.setItem("token", response.token);
      localStorage.setItem("expireDuration", now - expire);
      localStorage.setItem("expire", response.expire);
      return
    }

    // if dont have the token do something else
  }
  useEffect(() => {
     // 10min = 600000 milleseconds
     setInterval(refreshApi(), 600000)
  },[])

RefreshToken.js

module.exports = () => ({
 getRefreshToken: async (token) => {
   return new Promise((resolve, reject) => {
     fetch("https://localhost:3000/refreshToken", {
       method: "POST",
       headers: {
         "Authorization": `Bearer ${token}`
       },
       cache: "default"
     })
     .then(response => response.json())
     .then(responseInJSON => resolve(responseInJSON))
     .catch(err => reject(err))
   })
 } 
})
  1. You can use a third-party library, one that is used a lot is the axios.js, you can follow this example:

Api.js

import axios from 'axios'

const api = axios.create({ baseURL: 'http://localhos:3000' })

module.exports = {
  api
}

RefreshToken.js

import { api } from './Api'

module.exports = () => ({
 getRefreshToken: async (token) => {
   return api.get('/refreshToken', {
     headers: {
       "Authorization": `Bearer ${token}`
     }
   })
 } 
})
Sign up to request clarification or add additional context in comments.

7 Comments

Thank you so mush for your response it's really for helpful ,But my problem is that i want to call refresh token every 10 min ,Even if I refresh the page.
Ok, I've updated the answer a lite, check if this gives you some ideas.
That's work ,But when I refresh the , It seems that the counter returns to 0, and sometimes the token will be expired in this period.
If you use the Date.now(response.expire) maybe the expire date is in the wrong format, the best format to string dates is the ISO format en.wikipedia.org/wiki/ISO_8601.
For now ,I Just fix the duration on 600000
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.