0

I am trying to persist my mobx state in my react native app. It works most of the time but there are often errors where I have to create empty stores and lose the state. I would love some advice on how to better achieve this or if anyone has any idea of what could be causing this.

Here is how I am doing it.

main.tsx AppRegistry.registerComponent(APP_NAME, () => RootComponent)

root-component.tsx

export class RootComponent extends React.Component<{}, IRootComponentState> {
  public async componentDidMount(): Promise<void> {
    SplashScreen.hide()
    this.setState({ rootStore: await setupRootStore() })
  }

setup-root-store.ts

const ROOT_STATE_STORAGE_KEY = "root"

export async function setupRootStore(): Promise<IRootStore> {
  let rootStore: IRootStore
  let data: any

  const env = await createEnvironment()
  try {
    data = (await storage.load(ROOT_STATE_STORAGE_KEY)) || {}
    rootStore = RootStoreModel.create(data, env)
  } catch {
/// Errors out here
    rootStore = RootStoreModel.create({}, env)
  }

  if (__DEV__) {
    env.reactotron.setRootStore(rootStore, data)
  }

  onSnapshot(rootStore, (snapshot) => storage.save(ROOT_STATE_STORAGE_KEY, snapshot))

  return rootStore
}

There are times when it errors in the catch block and then I am just reinstating with empty stores. I have tried to log the catch error but its always undefined

Thanks!

elcapitan
  • 145
  • 1
  • 2
  • 13
  • Did you check whether the exception occurs on the first or second line of your `try` block? Depending on where it occurs, can you maybe post your `create` method? – Philipp Sumi Jul 14 '20 at 22:23
  • @PhilippSumi after logging I can confirm its failing on ```rootStore = RootStoreModel.create(data, env)``` Thats not a method that I created. Its a MOBX pattern to instantiate the store rather than doing new rootStore() – elcapitan Jul 15 '20 at 13:39
  • Are you sure `data` has all needed fields and correct types? Did you check it with console logging or something like that? – Danila Jul 15 '20 at 20:02
  • @Danila I was just coming to resolve this ticket. It turned out that a model deep in my project had a value like `weight: 0` And it was occasionally null. So it couldn't reinstantiate. I updated that type and it worked!! Thanks for everyones attention and help – elcapitan Jul 15 '20 at 21:05

0 Answers0