Mobx: How do you structure try/catch blocks?

Created on 6 Jul 2019  ยท  4Comments  ยท  Source: mobxjs/mobx

I'm using the container model pattern where I have a container that calls the action and the action calls the api.

Should I try/catch on my container or my store? There are places where I need to play with local state variables in the container, based on the response of try/catch. Does this yields to swallowing errors?

Here's an example:

Store.js

  @action.bound
  async fetchAllStrategies() {
    try {
      const res = await API.get('/strategies', { response: true });
      this.setStrategies(JSON.parse(res.data.body));
    } catch (err) {
      console.error(err);
    }
  }

Container.js

async componentDidMount() {
    try {
      await Store.fetchAllStrategies();
      this.setState({ isLoading: false });
    } catch (err) {
      console.error(err);
      this.setState({ hasError: true });
      this.setState({ isLoading: false });
    }
  }

EDIT: fixed async action

โ” question

All 4 comments

You should probably read more about action and async/await. What you did in the first example means that you are modifying state out of action ... https://mobx.js.org/best/actions.html

Personally, I am doing error handling in lower-level api which bubbles up in case of need, but I am using React Hooks and GraphQL, so that's quite a different approach.

Thanks, I fixed the first example by moving state modification to an external action.

The examples the link show are mainly when you have state variables inside a store. isLoading, hasError

maybe we should start with the question: what will happen in the store on error?
if the error only affects the component using this method, I would take @FredyC's approach

if it affects the store too in other methods, maybe you should consider store state variable as the example shows

This thread has been automatically locked since there has not been any recent activity after it was closed. Please open a new issue for related bugs or questions.

Was this page helpful?
0 / 5 - 0 ratings