Mobx-state-tree afterCreate() not synchronous in react native

1.2k Views Asked by At

I am trying to load my application initialState by performing a load() function in the afterCreate() of my UserModel. What I am trying to do is to load an Authenticated page instead of a Login page if I detect that the accessToken is not empty in the UserStore.

However the page renders before the afterCreate() load function is ran. Which ends up always leading me to the login page.

I followed mainly this video tutorial by egghead.io but I am not sure why it's not working in my case.

I'm really stuck and any suggestions is appreciated!

The way I am passing my store is passing in the store using Provider in my App.js.

UserModel.js

const User = types
  .model("User", {
    accessToken: types.string
  })
  .actions(self => ({
    afterCreate() {
      self.load();
    },
    load: flow(function*() {
      const localData = yield LocalDB.get("user");
      applySnapshot(self, localData);
    })

  }));

The object LocalDB is just a wrapper around AsyncStorage to help parse the data into json format.

LocalDB.js

const LocalDB = {    
  get: async function(key) {
    try {
      let value = await AsyncStorage.getItem(key);

      try {
        return JSON.parse(value);
      } catch (err) {
        return value;
      }
    } catch (err) {
      console.error(err);
      return false;
    }

App.js

let store = UserStore.create({...})
export default class App extends Component {
  render() {
    return (
      <Provider store={store}>
        <Router />
      </Provider>
    );
  }
}
1

There are 1 best solutions below

0
On

Seems like I found the issue. I was initializing my store with some default variables at the start like this:

let store = UserStore.create({accessToken: ""})

Once I updated it to null it works fine.

let store = UserStore.create({accessToken: null})