swagger-typescript-api icon indicating copy to clipboard operation
swagger-typescript-api copied to clipboard

Requests are sent before auth header is set

Open Matzielab opened this issue 2 years ago • 2 comments

I'm using this library and using react query around it. I've noticed that there is no way to check if the security data has been set so the requests are called before the auth header is set, resulting in a lot of forbidden requests. Is there something im missing or how can i fix this?

example of useEffect where i'm setting security data when token has been updated on useUser

useEffect(() => {
    if (user.token) {
      API.setSecurityData({ token: user.token })
    } else {
      API.setSecurityData(null)
    }
  }, [user])

example of request that fire too early

const userInfoQuery = useQuery(
    ["USER_INFO", user.token],
    () => API.user.selfList(),
    {
      enabled: !!user.token,
    }
  )

i wish i could set enabled: to something else like API.securityDataIsSet but as far as i can see i can't even await for the securityData function to finish.

Matzielab avatar Jun 04 '23 10:06 Matzielab

I created a PR with a solution to this. Have also tested it in my project. You can see the PR here https://github.com/acacode/swagger-typescript-api/pull/538

And my code example from above would then be formatted like so:

const userInfoQuery = useQuery(
    ["USER_INFO", API.hasSecurityData],
    () => API.user.selfList(),
    {
      enabled: API.hasSecurityData,
    }
  )

Matzielab avatar Jun 05 '23 05:06 Matzielab

This happens to me when I build NextJS but not while developing.

Seems like adding this to the http-client.ts is enough for me, but wonder why this is not a feature.

public hasSecurityData = () => Boolean(this.securityData);

V-iktor avatar Feb 15 '24 11:02 V-iktor