DEV Community

Cover image for Create Mobx Store In React Native using Hooks & Combining multiple stores
Abhishek Tomar
Abhishek Tomar

Posted on

Create Mobx Store In React Native using Hooks & Combining multiple stores

Create your stores

interface Todo {
  id: number;
  text: string;
}
class TodoStore {
  root: RootStore;
  listTodo: Todo[] = [];
  constructor(root: RootStore) {
    makeAutoObservable(this);
    this.root = root;
  }
  setTodo(todo: Todo) {
    this.listTodo.push(todo);
  }

  get getTodoAll() {
    return this.listTodo;
  }

  getTodoId(id: number) {
    return this.listTodo.filter((f) => f.id == id);
  }
}

class OtherStore {
  root: RootStore;
  totalTodoCount: number = 0;
  constructor(root: RootStore) {
    makeAutoObservable(this);
    this.root = root;
  }

  init() {
    // safe to access other stores
    const allData = this.root.todo.getTodoAll;
    this.totalTodoCount = allData.length;
  }
}
Enter fullscreen mode Exit fullscreen mode

Create root store & combine all stores in root

class RootStore {
  todo: TodoStore;
  other: OtherStore;
  constructor() {
    this.todo = new TodoStore(this);
    this.other = new OtherStore(this);

    this.other.init();
  }
}

Enter fullscreen mode Exit fullscreen mode

Create Provider

let store: RootStore;
const StoreContext = createContext<RootStore | undefined>(undefined);
export default function RootStoreProvider({children}: {children: ReactNode}) {
  const root = store ?? new RootStore();
  return <StoreContext.Provider value={root}>{children}</StoreContext.Provider>;
}
Enter fullscreen mode Exit fullscreen mode

Create hooks for accessing the store

export function useRootStore() {
  const context = useContext(StoreContext);
  if (context === undefined) {
    throw new Error('useRootStore must be used within RootStoreProvider');
  }
  return context;
}

Enter fullscreen mode Exit fullscreen mode

Create UI screen

const AppScreen1 = observer(() => {
  const store = useRootStore();
  const AddNew = () => {
    const ID = Math.floor(1000 + Math.random() * 9000);
    store.todo.setTodo({id: ID, text: `Todo Item ${ID}`});
  };
  return (
    <View style={{flex: 1}}>
      {store.todo.getTodoAll.map((item) => {
        return (
          <Text style={{fontWeight: 'bold'}}>
            {item.id.toString()}/{item.text}
          </Text>
        );
      })}
      <Button title="Add New Todo" onPress={AddNew} />
    </View>
  );
});
Enter fullscreen mode Exit fullscreen mode

Create app entry

export const AppEntry = () => {
  return (
    <RootStoreProvider>
      <AppScreen1 />
    </RootStoreProvider>
  );
};

Enter fullscreen mode Exit fullscreen mode

Thanks,

https://dev.to/ivandotv/mobx-root-store-pattern-with-react-hooks-318d
https://mobx.js.org/README.html
https://github.com/leighhalliday/mobx2021/blob/main/src/store.tsx
https://unsplash.com/photos/vc3iVL_znJ8

Top comments (0)

Some comments may only be visible to logged-in visitors. Sign in to view all comments.