Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Cannot call request api 401 again after get new acccessToken when using react-query #283

Open
ducyb782001 opened this issue May 9, 2024 · 0 comments

Comments

@ducyb782001
Copy link

Hi every one, i have api.ts file like that

const client = axios.create({
  url: process.env.NEXT_PUBLIC_BASE_URL,
  headers: {
    "x-api-key": process.env.NEXT_PUBLIC_DGG_API_KEY,
  },
})

export const refreshAccessToken = async () => {
  const cookies = cookie.parse(window?.document.cookie)

  const onSuccess = (response) => {
    const data = response?.data
    processDataLogin(data)
  }

  const onError = (error) => {
    localStorage.clear()
    window.document.cookie = cookie.serialize("accessToken", "", {
      maxAge: -1, // Expire the accessToken immediately.
      path: "/",
    })
    window.document.cookie = cookie.serialize("refreshToken", "", {
      maxAge: -1, // Expire the refreshToken immediately.
      path: "/",
    })
    browserRedirectToIndexAfterSignOut()
    return error
  }

  const payload = {
    refreshToken: cookies.refreshToken,
  }

  if (cookies.refreshToken && !cookies.accessToken) {
    try {
      const response = await client({
        method: "post",
        url: refreshAccessTokenUrl,
        data: payload,
      })
      onSuccess(response)
    } catch (error) {
      onError(error)
    }
  }
}

export const requestAPI = async ({ ...options }) => {
  console.log("Call to request api", options)
  const cookies = cookie.parse(window?.document.cookie)
  const acceptLanguage = localStorage.getItem("i18nextLng")
  if (cookies.accessToken) {
    console.log("Go line 96: ", cookies)
    client.defaults.headers.common.Authorization = `Bearer ${cookies?.accessToken || ""}`
  }

  if (acceptLanguage) {
    client.defaults.headers.common["Accept-Language"] = acceptLanguage
  }

  const onSuccess = (response) => response
  const onError = async (error) => {
    return error
  }
  return client(options).then(onSuccess).catch(onError)
}

createAuthRefreshInterceptor(client, refreshAccessToken)

I add some log and i realize after one request get 401 error. It will call refresh api immediately => get new accessToken and then call api again. But new api don't have accessToken.
It quite strang, any one can help me?
image

My version is:

"axios": "^0.27.2",
"axios-auth-refresh": "^3.3.6",
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant