Skip to content

Instantly share code, notes, and snippets.

@afflicted-cat
Last active September 27, 2021 10:01
Show Gist options
  • Save afflicted-cat/25f84118c76bdfbd4e4b8e7695b2f82b to your computer and use it in GitHub Desktop.
Save afflicted-cat/25f84118c76bdfbd4e4b8e7695b2f82b to your computer and use it in GitHub Desktop.
Nextjs ssr
module.exports = (api) => {
api.cache.using(() => process.env.NODE_ENV);
return {
presets: ["next/babel"],
plugins: [["effector/babel-plugin", { reactSsr: true }]],
};
};
import { fork, allSettled, serialize, Unit } from "effector";
export async function getInitialState<P>(unit: Unit<P>, params?: P) {
const scope = fork();
await allSettled(unit, { scope, params });
const initialState = serialize(scope);
return { scope, props: { initialState } };
}
import { createStore, createEvent } from "effector";
const pageRequested = createEvent<GetServerSidePropsContext>();
const $is404 = createStore(false);
export async function getServerSideProps(context: GetServerSidePropsContext) {
const { props, scope } = await getInitialState(pageRequested, context);
return { props, notFound: scope.getState($is404) };
}
import { fork, serialize, Scope } from "effector";
import { Provider } from "effector-react/ssr";
import { ComponentType } from "react";
import { AppProps } from "next/app";
interface InitialState {
initialState?: Object;
}
export function withScope() {
const isServer = typeof window === "undefined";
let clientScope: Scope;
return (Component: ComponentType<AppProps<InitialState>>) => {
return (props: AppProps<InitialState>) => {
// prettier-ignore
const { pageProps: { initialState = {} } } = props;
const scope = fork({
values: {
...(clientScope ? serialize(clientScope) : {}),
...initialState,
},
});
if (!isServer) clientScope = scope;
return (
<Provider value={scope}>
<Component {...props} />
</Provider>
);
};
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment