sokida
sokida

Reputation: 531

How to programatically call an api in react js

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 ?

Upvotes: 0

Views: 52

Answers (1)

ralvescosta
ralvescosta

Reputation: 56

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}`
     }
   })
 } 
})

Upvotes: 1

Related Questions