ssrSafe.ts
This file
Path
src/middleware/ssrSafe.ts
25 lines · 847 bytes · TypeScript
Last changed by
experimental: unstable ssrSafe middleware (#3308)Daishi Katobefore adoptionf999022
History of this fileTake it
experimental: unstable ssrSafe middleware (#3308)Daishi Katobefore adoptionf999022
lines 1–25why, one step back1import type { StateCreator, StoreMutatorIdentifier } from '../vanilla.ts'23// This is experimental middleware. It will be changed before finalizing it.4// https://github.com/pmndrs/zustand/discussions/27405// TODO Not very happy with the middleware name. Will revisit it later.6export function ssrSafe<7 T extends object,8 U extends object,9 Mps extends [StoreMutatorIdentifier, unknown][] = [],10 Mcs extends [StoreMutatorIdentifier, unknown][] = [],11>(12 config: StateCreator<T, Mps, Mcs, U>,13 isSSR: boolean = typeof window === 'undefined',14): StateCreator<T, Mps, Mcs, U> {15 return (set, get, api) => {16 if (!isSSR) {17 return config(set, get, api)18 }19 const ssrSet = () => {20 throw new Error('Cannot set state of Zustand store in SSR')21 }22 api.setState = ssrSet23 return config(ssrSet as never, get, api)24 }25}