Skip to content

Commit f999022

Browse files
authored
experimental: unstable ssrSafe middleware (#3308)
* unstable ssrSafe * add todo comment
1 parent 8280650 commit f999022

File tree

2 files changed

+26
-0
lines changed

2 files changed

+26
-0
lines changed

src/middleware.ts

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,3 +14,4 @@ export {
1414
type PersistStorage,
1515
type PersistOptions,
1616
} from './middleware/persist.ts'
17+
export { ssrSafe as unstable_ssrSafe } from './middleware/ssrSafe.ts'

src/middleware/ssrSafe.ts

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
import type { StateCreator, StoreMutatorIdentifier } from '../vanilla.ts'
2+
3+
// This is experimental middleware. It will be changed before finalizing it.
4+
// https://github.com/pmndrs/zustand/discussions/2740
5+
// TODO Not very happy with the middleware name. Will revisit it later.
6+
export 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 = ssrSet
23+
return config(ssrSet as never, get, api)
24+
}
25+
}

0 commit comments

Comments
 (0)