Skip to content

Using a persisted store with createContext and TypeScript #882

Closed
@linuxlewis

Description

@linuxlewis

Hi all,

We're using the store persistence in conjunction with a context to provide the store to all parts of the application. Since the persist callback modifies the returned useStore hook we are having trouble getting TypeScript to recognize the persist property of the hook.

We tried modifying the create type itself to match the middleware tests as indicated in the code comment(https://github.com/pmndrs/zustand/blob/main/src/middleware/persist.ts#L91):

const useStore = create<
        IStore,
        SetState<IStore>,
        GetState<IStore>,
        Mutate<StoreApi<IStore>, [['zustand/persist', Partial<IStore>]]>
    >(

However this didn't solve our root issue because we are accessing useStore from a context. Looking at the createContext function I'm not sure how to pass in the correct types so useStore has the persist property. How do you intend to use both persist and createContext with TypeScript? https://github.com/pmndrs/zustand/blob/main/src/context.ts#L15
https://github.com/pmndrs/zustand/blob/main/src/context.ts#L60

I can provide a PR with proposed changes if that is preferred.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions