ConrabOpto / mst-query

Query library for mobx-state-tree
MIT License
116 stars 8 forks source link

How to configure rootstore? #16

Closed vbylen closed 2 years ago

vbylen commented 2 years ago

Say the the rootstore was already configured (based on this example):

import { Instance, onSnapshot, types } from "mobx-state-tree";
import { createContext, useContext } from "react";
import { Cart } from "./Cart";
import { Counter } from "./Counter";

const RootModel = types.model({
  counter: Counter,
  cart: Cart,
});

let initialState = RootModel.create({
  counter: {
    count: 0,
  },
  cart: { items: [] },
});

if (process.browser) {
  const data = localStorage.getItem("rootState");
  if (data) {
    const json = JSON.parse(data);
    if (RootModel.is(json)) {
      initialState = RootModel.create(json);
    }
  }
}

export const rootStore = initialState;

onSnapshot(rootStore, (snapshot) => {
  console.log("Snapshot: ", snapshot);
  localStorage.setItem("rootState", JSON.stringify(snapshot));
});

export type RootInstance = Instance<typeof RootModel>;
const RootStoreContext = createContext<null | RootInstance>(null);

export const Provider = RootStoreContext.Provider;
export function useMst() {
  const store = useContext(RootStoreContext);
  if (store === null) {
    throw new Error("Store cannot be null, please add a context provider");
  }
  return store;
}

How should one go about converting it to use mst-query?

Thanks!

k-ode commented 2 years ago

You currently can't as it complicates types. But I don't see why you shouldn't be able to just change how you setup your store to use createRootStore instead.

vbylen commented 2 years ago

@k-ode please correct me if I'm wrong but does that mean that in the above code all I need to do differently is use RootModel.createRootStore instead of RootModel.create?

k-ode commented 2 years ago

I'm working on converting some mobx-state-tree examples into using mst-query. It's not complete yet, but you should be able to get a general idea for how this could be done here: https://codesandbox.io/s/books-mst-query-0kljt?file=/src/stores/RootStore.ts

Note how RootStore is created by createRootStore and bookStore is created by createModelStore. While CartStore and ViewStore are just normal properties, since they don't handle items with identifiers.