Skip to content

Commit

Permalink
add types
Browse files Browse the repository at this point in the history
  • Loading branch information
nitedani committed Dec 28, 2023
1 parent f21266a commit 492e93a
Show file tree
Hide file tree
Showing 2 changed files with 47 additions and 5 deletions.
6 changes: 3 additions & 3 deletions examples/zustand/store.ts
Original file line number Diff line number Diff line change
@@ -1,18 +1,18 @@
export { useStore }

import { create, server } from 'vike-react-zustand'
import { create, server, withPageContext } from 'vike-react-zustand'

interface Store {
counter: number
setCounter: (value: number) => void
serverEnv: string
}

const useStore = create<Store>(
const useStore = create<Store>()(
(
set,
get
/* TODO
/* TODO
pageContext
*/
) => ({
Expand Down
46 changes: 44 additions & 2 deletions packages/vike-react-zustand/src/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,42 @@ export { create, server }
import { useContext } from 'react'
import { getContext, setCreateStore } from './renderer/context.js'
import { create as create_ } from 'zustand'
import type { StoreMutatorIdentifier, UseBoundStore, Mutate, StoreApi as ZustandStoreApi } from 'zustand'

function create(createStore: any): any {
setCreateStore(() => {
type Create = {
<T, Mos extends [StoreMutatorIdentifier, unknown][] = []>(
initializer: StateCreator<T, [], Mos>
): UseBoundStore<Mutate<ZustandStoreApi<T>, Mos>>
<T>(): <Mos extends [StoreMutatorIdentifier, unknown][] = []>(
initializer: StateCreator<T, [], Mos>
) => UseBoundStore<Mutate<ZustandStoreApi<T>, Mos>>
/**
* @deprecated Use `useStore` hook to bind store
*/
<S extends ZustandStoreApi<unknown>>(store: S): UseBoundStore<S>
}

type Get<T, K, F> = K extends keyof T ? T[K] : F
export type StateCreator<
T,
Mis extends [StoreMutatorIdentifier, unknown][] = [],
Mos extends [StoreMutatorIdentifier, unknown][] = [],
U = T
> = ((
setState: Get<Mutate<ZustandStoreApi<T>, Mis>, 'setState', never>,
getState: Get<Mutate<ZustandStoreApi<T>, Mis>, 'getState', never>,
store: Mutate<ZustandStoreApi<T>, Mis>
) => U) & {
$$storeMutators?: Mos
}

const create: Create = ((createState: any) => {
return createState ? createImpl(createState) : createImpl
}) as any

function createImpl(createStore: any): any {
// @ts-ignore
setCreateStore((pageContext: any) => {
return create_(createStore)
})

Expand All @@ -26,3 +59,12 @@ function server<T extends Record<string, any>>(fn: () => T) {
}
return {} as T
}
type StoreAndHook = ReturnType<typeof create>
function withPageContext<S extends StoreAndHook>(storeCreatorCreatorFn: (pageContext: StoreAndHook) => S) {
//@ts-ignore
// createImpl._withPageContext_ = storeCreatorFn
// const storeCreatorFn = () => {
// storeCreatorCreatorFn(pageContext)
// return createImpl(storeCreatorFn)
// }
}

0 comments on commit 492e93a

Please sign in to comment.