5

When an API returns a 401, I want to force logout the user. The following code is written inside a React Native Ignite project using Mobx

import { useStores } from "../../models"
this.apisauce.axiosInstance.interceptors.response.use(response => {
  return response;
}, error => {
  if (error.response.status === 401) {
    useStores().authStore.reset()
  }
  return error;
})

The call to authStore.reset() doesn't happen, no error, no console.tron.log, just nothing. Is there a better practice to capture 401 and trigger a mobx action? Without handling it at each individual action that calls into the API?

AnonymousSB
  • 3,516
  • 10
  • 28
  • It seems like you are using React hook inside non-react code? I don't think this is supposed to work that way! Why not just import your store directly? – Danila Mar 11 '21 at 13:12
  • 1
    @Danila That's exactly question. Are you suggesting that instead of using `useStore` from the root-store, I should just import the file that contains the `reset()` method and call that directly? The `reset()` method clears out the mobx store, which causes the app to reset to login screen. Currently I have to, inside very mobx store, handle a 401 from every method that calls an API. It's not scalable, and there's got to be a more streamlined way. – AnonymousSB Mar 15 '21 at 20:35

1 Answers1

0

In my case:

// file auth.store.js
class AuthStore {

  ...
  reset(){ ... }
}

export default new AuthStore();
// file models.js
import authStore from 'path/to/file/auth.store.js';

export default { authStore };
// file api-file.js
import useStores from 'path/to/file/models.js';

this.apisauce.axiosInstance.interceptors.response.use(response => {
  return response;
}, error => {
  if (error.response.status === 401) {
    useStores.authStore.reset();
  }
  return error;
})

Nak
  • 251
  • 1
  • 6