I use mobx-state-tree on my NextJS app with Server Side Rendering. On the server only, I fetch an API to load some information and add to my Store. But after the client load, my store is cleared because I need to instantiate on server AND client. That's my problem.
My store :
const Store = types
.model('Store', {
user: types.compose(User),
});
const createStore = Store.create({
user: {},
});
let store = null;
/**
* Init store
*
* @param {bool} isServer
* @param {object} snapshot
*/
const initStore = (isServer, snapshot = null) => {
if (isServer) {
store = createStore;
}
if (store === null) {
store = createStore;
}
if (snapshot) {
applySnapshot(store, snapshot);
}
return store;
};
My component on client side :
static getInitialProps({ req }) {
const isServer = !!req;
const store = initStore(isServer);
return { initialState: getSnapshot(store), isServer }
}
constructor(props) {
super(props);
this.store = initStore(props.isServer, props.initialState);
}
And my User store :
const User = types
.model('User', {
name: types.optional(types.string, ''),
first_name: types.optional(types.string, ''),
})
.actions(self => {
function load(name) {
self.name = name;
};
async function afterCreate() {
if (IS_SERVER) {
const request = await callApi();
return self.load(request.user.name);
}
};
return {
load,
afterCreate
};
})
.views(self => ({
get userName() {
return self.name;
},
}));
My actions self.load(name) is working but removed on client sideloaded.
Anyone know how I can "save" the user store from the server side?
Thank you!