2020/01/29
MobX Provider: The set of provided stores has changed. Please avoid changing stores as the change might not propagate to all children
import { useStaticRendering } from 'mobx-react';
import CounterStore from './counter';
import PlusStore from './plus';
const isServer = typeof window === 'undefined';
useStaticRendering(isServer);
let store = null;
export default function initializeStore(initialData) {
if (isServer) {
return {
counter: new CounterStore(),
plus: new PlusStore(),
};
}
if (store === null) {
store = {
counter: new CounterStore(),
plus: new PlusStore(),
};
}
return store;
}
import React from 'react';
import App, { Container } from 'next/app';
import Head from 'next/head';
import { globalStyles } from '../styles/reset';
import { Provider } from 'mobx-react';
import initializeStore from '../stores/stores';
class MyApp extends App {
static async getInitialProps(appContext) {
const mobxStore = initializeStore();
appContext.ctx.mobxStore = mobxStore;
const appProps = await App.getInitialProps(appContext);
return {
...appProps,
initialMobxState: mobxStore,
};
}
constructor(props) {
super(props);
const isServer = typeof window === 'undefined';
this.mobxStore = isServer
? props.initialMobxState
: initializeStore(props.initialMobxState);
}
render() {
const { Component, pageProps } = this.props;
return (
<Provider {...this.mobxStore}>
<Head>
<meta charSet="utf-8" />
<style type="text/css">{globalStyles}</style>
<title>DeusAdventures</title>
</Head>
<Container>
<Component {...pageProps} />
</Container>
</Provider>
);
}
}
export default MyApp;
import React, { Component } from 'react';
import { observer, inject } from 'mobx-react';
@inject('counter')
@observer
class Counter extends Component {
render() {
const { counter } = this.props;
return (
<div>
<h1>{counter.number}</h1>
<button onClick={counter.increase}>+1</button>
<button onClick={counter.decrease}>-1</button>
</div>
);
}
}
export default Counter;