Skip to content

SWR keeps refreshing with old bearer token #852

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

Closed
vanam opened this issue Jan 2, 2021 · 1 comment · Fixed by #853
Closed

SWR keeps refreshing with old bearer token #852

vanam opened this issue Jan 2, 2021 · 1 comment · Fixed by #853
Labels
bug Something isn't working

Comments

@vanam
Copy link

vanam commented Jan 2, 2021

Bug report

Description / Observed Behavior

I have encountered strange behavior when accessing endpoints with bearer token. I have a fetcher like this:

const fetcherWithToken = async (url, token) => {
  try {
    const response = await fetch(url, {
      headers: {
        'Authorization': 'Bearer ' + token
      },
    })

    let text = await response.text()

    const data = text ? JSON.parse(text) : null

    if (response.ok) {
      return data
    } else if (response.statusCode === 401) {
      const error = new NotAuthorizedError(response.statusMessage);
      error.status = response.status
      throw error
    }

    const error = new Error(response.statusText)
    error.response = response
    error.status = response.status
    error.data = data
    throw error
  } catch (error) {
    if (!error.data) {
      error.data = { message: error.message }
    }
    throw error
  }
}

and a hook like this:

const { data, error } = useSWR(
    ["https://api.example.com/xxx", token],
    fetcherWithToken,
    { refreshInterval: 5000 }
  );

After token refresh SWR keeps refreshing with both tokens - the old and the new.

Expected Behavior

I would expect SWR to refresh only with the new token.

Repro Steps / Code Example

Source code: https://codesandbox.io/s/eager-hoover-v4ryk?file=/pages/index.js

  1. Let the app refresh data several times
  2. Click at "Click me" button as soon as possible after a new message ("Fetching with Bearer token: X") in console appears
    swr-keeps-refreshing-with-old-token

Additional Context

swr: 0.3.11

I have come across this problem when building next.js application with @react-keycloak/ssr.

PS: I am not a JS developer so the code is a mess and it might just be PEBCAK.

@vanam
Copy link
Author

vanam commented Jan 3, 2021

Thank you

shuding pushed a commit that referenced this issue Jan 4, 2021
* add test for #852

* improve assert
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug Something isn't working
Projects
None yet
Development

Successfully merging a pull request may close this issue.

2 participants