Gabotronix's avatar

React Native: access mobx store action/variable inside another store

Hi everybody, I'm a react-native newbie, I'm using mobx for state management, I set up my app to use context API and hooks to utilize stores in my components easily, I got this implementation from mobx-react native docs.

  1. Issue is I want to invoke an action and use observables from themeStore inside my postStore, how can I do that, is that even possible? in the past with vuex I was able to do it pretty easily.

  2. Is this mobx + context + hooks implementation good?

First I set up context:

//contexts/index.js

import React from 'react'
import { configure } from 'mobx';
import { ThemeStore }  from '../stores/ThemeStore.js'
import { PostStore }  from '../stores/PostStore.js'

export const storesContext = React.createContext({
  postStore: new PostStore(),
  themeStore: new ThemeStore(),
});

configure({ enforceActions: "observed" });

Then I created use-stores hook which I import into the components I want to invoke store actions and variables from:

//hooks/use-stores.js

import React from 'react'
import { storesContext } from '../contexts/index.js'

export const useStores = () => React.useContext(storesContext);

That way in my app I can do:

import { useStores } from '@hooks/use-stores'

const { postStore, themeStore } = useStores();

My stores are normal mobx stores, they contain observables, actions and flow actions for async/await operations.


import { observable, computed, action, flow } from "mobx";

export class PostStore
{
    @observable postCount = 0;

    @action.bound increasePostCount()
    {
        this.postCount++;
    }
}

0 likes
0 replies

Please or to participate in this conversation.