Last active
September 27, 2021 10:01
-
-
Save afflicted-cat/25f84118c76bdfbd4e4b8e7695b2f82b to your computer and use it in GitHub Desktop.
Nextjs ssr
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module.exports = (api) => { | |
api.cache.using(() => process.env.NODE_ENV); | |
return { | |
presets: ["next/babel"], | |
plugins: [["effector/babel-plugin", { reactSsr: true }]], | |
}; | |
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 } }; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) }; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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