Ming
Ming

Reputation: 1602

Reactjs : error boundary with mobx async call

Hello I'm trying to implement error boundary to my system, but I'm having problems I have an asynchronous call to my api, to check if the backend is up and if the browser session is auth, for testing I left my backend on, but my fallback was not called, I'm using lib: react-error-boundary If anyone can help me with this I am grateful

error:

enter image description here Store:

  public initApi = async (): Promise<void> => {
    this.appState = 'pending'
    try {
      const response = await this.AxiosStore.get('/')
      if (!response) return Promise.reject(new Error('Service Unavaliable'))
      return runInAction(() => {
        if (response.data.acess_token)
          this.currentUserStore.accessToken = response.data.access_token
        this.appState = 'fulfilled'
      })
    } catch (error) {
      runInAction(() => {
        this.appState = 'error'
      })
      return Promise.reject(error)
    }
  }
}

App:

const AuthApp: React.FC<{
  isAuth: boolean
}> = observer(({isAuth}) => {
  return (
    <>
      {isAuth ? (
        <Suspense fallback={<h1>fb</h1>}>
          <DashBoard />
        </Suspense>
      ) : (
        <Suspense fallback={<h1>login</h1>}>
          <LoginPage />
        </Suspense>
      )}
    </>
  )
})

const App: React.FC = observer(() => {
  const {
    layoutStore,
    initApi,
    appState,
    currentUserStore,
    authStore,
  } = useRootStore()
  const handleError = useErrorHandler()
  useEffect(() => {
    if (appState !== 'fulfilled') initApi().catch((error) => handleError(error))
  }, [])
  return (
    <ThemeProvider theme={layoutStore.isDarkMode ? darkTheme : lightTheme}>
      <GlobalReset />
      <ErrorBoundary FallbackComponent={ErrorFallback}>
        {appState === 'fulfilled' ? <AuthApp isAuth={authStore.isAuth} /> : 'b'}
      </ErrorBoundary>
    </ThemeProvider>
  )
})

Upvotes: 0

Views: 670

Answers (1)

Ivan V.
Ivan V.

Reputation: 8081

You need to handle the async scenario with error, react-error-boundary has a special hook for that.

  // create the hook
  const handleError = useErrorHandler() //hook from the react-error-boundary
  
  // pass error in the catch block to the hook
  yourAsyncFunction().catch(e => handleError(e))

Or with try/catch:

try{
  await yourAsyncFunction()
}
catch(e){
  handleError(e)
}

Upvotes: 1

Related Questions