aribouius / jsonapi-react

A minimal JSON:API client and React hooks for fetching, updating, and caching remote data.
MIT License
149 stars 28 forks source link

onError for ApiClient #8

Closed webdobe closed 4 years ago

webdobe commented 4 years ago

I am trying to figure out the best way to handle when a JWT token expires. What is the best way to redirect to logout?

In apollo I could do something like this:

import { onError } from 'apollo-link-error';

const logoutLink = onError(({ networkError }) => {
 if (networkError.statusCode === 401) logout();
})

const apolloClient = new ApolloClient({
  link: logoutLink.concat(concat(authMiddleware, httpLink)),
  cache: new InMemoryCache(),
});

Right now the way I can do this is by either wrapping the client in a custom hook OR on every call check for a 401.

Obviously my own hook is elegant enough, but would be cool if I could just do something like apollo client.

Thoughts? Am I missing something in the client?

aribouius commented 4 years ago

Hey @webdobe the way our app currently handles this is by attaching a listener to the client instance, and just checking for an error object, which if present, is the error hash returned from your API.

const client = useClient()

useEffect(() => {
  return client.subscribe(action => {
    if (action.error && action.error.status === '401') {
      session.destroy()
    }
  })
}, [])

The action object there is not currently documented, but you can see how it gets dispatched here: https://github.com/aribouius/jsonapi-react/blob/master/src/client.js#L189. I'll likely add a better way to handle this via something similar as Apollo (e.g. onError), but this should work for now.

aribouius commented 4 years ago

@webdobe i just published a change that adds a client.onError method. Given it could be used inside of a component, it returns a unsubscribe function that should be called when the component is unmounted.

Relevant PR here.

Let me know if this works for your use-case!

webdobe commented 4 years ago

Awesome! Thank you @aribouius