mobxjs / mobx-react

React bindings for MobX
https://mobx.js.org/react-integration.html
MIT License
4.85k stars 350 forks source link

Isn't it possible to create inheritance between two mobx stores? #862

Closed bum-hyun closed 4 years ago

bum-hyun commented 4 years ago

For avoiding duplication, I did like below

common.ts

export default class Common {

  constructor(type?: number) {
    if(type)
    this.data.dealTypeId = type;
  }
}

saleStore.ts

export default class SaleStore extends Common {}

purchase.ts

export default class PurchaseStore extends Common {}

index.ts

export const storesContext = React.createContext({
  saleStore: new SaleStore(1),
  purchaseStore: new PurchaseStore(2),
});

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

in component

  const { saleStore, purchaseStore } = useStores();
  useEffect(() => {
    console.log(saleStore.data.dealTypeId)
    console.log(purchaseStore.data.dealTypeId)
  }, []);

And, results are 2, 2 It seems like overriding

mweststrate commented 4 years ago

It depends on what this.data is, which can't be told from your code example, if the object this.data is shared, then yes the dealTypeId is shared. Please provide a sandbox reproduction and clarify how this issue is related to MobX since it is filed in this repo, as I don't see a single line related to MobX so far in your question.

bum-hyun commented 4 years ago

Oh...It's my fault That part wasn't the cause. I should have used @computed, but I used @get if @get is in Store, It's not inheriting properly.