delboy1978uk
delboy1978uk

Reputation: 12375

React native image with Auth Token header, how to handle 401?

I have a React Native app which connects to an OAuth2 backend. I am using Axios to connect to the API, and I have a request and response interceptor which can handle when an access token runs out, it will fetch a fresh access token using the refresh token, whilst queuing any other asynchronous requests until we have our new toke.

All of that works great, but now I have protected image resources to serve, and I'm unsure how to deal with it.

Using the React Native Image component, we can pass in headers easily enough:

<Image source={{
    headers: {Authorization: 'Bearer ' + authToken }, 
    uri: uri
}}></Image>

So yes, I can display my protected images without issue, but I need to find a way to achieve the same token refreshing functionality with the images as I do with the Axios client.

Is it possible using the React Native Image component, like a 401 callback function, or is there a library that possibly I can use for this?

Thanks in advance for any help or suggestions. 😀

Upvotes: 2

Views: 429

Answers (1)

user18309290
user18309290

Reputation: 8320

Use onError to trigger a token refresh.

<Image
  headers: {Authorization: 'Bearer ' + authToken }, 
  uri: uri
  onError={(error) => { /*TODO*/ }}
/>

Upvotes: 3

Related Questions