Skip to content

Instantly share code, notes, and snippets.

@belozer
Last active August 21, 2019 19:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save belozer/8edce46775acafc8ffd5c80ff4a340ed to your computer and use it in GitHub Desktop.
Save belozer/8edce46775acafc8ffd5c80ff4a340ed to your computer and use it in GitHub Desktop.
NextJS effector
{
"presets": ["next/babel"],
"plugins": ["effector/babel-plugin"]
}
import Document, { Html, Head, Main, NextScript } from 'next/document'
import { appState } from '../src/store';
class MyDocument extends Document {
render() {
return (
<Html>
<Head />
<body>
<Main />
<NextScript />
<script dangerouslySetInnerHTML={{__html: `window.__INITIAL_DATA__ = ${JSON.stringify(appState)}`}} />
</body>
</Html>
)
}
}
export default MyDocument
import { createDomain } from 'effector';
export const domain = createDomain('App');
export const { event: createEvent, store: createStore } = domain;
export const appState = {} as any;
domain.onCreateStore(store => {
const { sid } = (store as any).defaultConfig;
if (typeof window !== 'undefined') {
// Fill stores
const data = (window as any).__INITIAL_DATA__
if (data[sid]) store.defaultState = data[sid];
store.setState(store.defaultState);
} else {
// Collect data from stores for push to client side
store.watch(state => appState[(store as any).defaultConfig.sid] = state);
}
});
// Use app domain for create stores
import { createStore, createEvent } from '.';
import { IProduct } from '../typings/Product';
type Dictionary = {
[key: string]: IProduct | null
}
export const addProduct = createEvent<IProduct>();
export const setProducts = createEvent<Dictionary>();
export const removeProduct = createEvent<number>();
export const productsStore = createStore<Dictionary>({})
.on(setProducts, (_state, payload: Dictionary) => payload)
.on(addProduct, (state, product: IProduct) => ({
...state,
[product.id]: product
}))
.on(removeProduct, (state, productId: number) => ({
...state,
[productId]: null
}));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment