Pawan
Pawan

Reputation: 857

How to use zustand devtools with typescript?

I am trying to use devtools feature of zustand. I am also using typescript. When I pass the store to devtools my whole store code throws error as: Argument of type 'StateCreator<Store, [], [["zustand/devtools", never]], Store>' is not assignable to parameter of type 'StateCreator<Store, [], [], Store>'.

Here is my store code:

const useUserStore = create<Store>(devtools((set) => ({
    token: "",
    isLogged: false,

    loginUser: (jwtToken: string) => {
        set((state) => ({
            ...state,
            token: jwtToken,
            isLogged: true,
        }));
    },

    logoutUser: () => {
        set((state) => ({
            ...state,
            token: "",
            isLogged: false,
        }));
    },
})));

Here is the Store type:

export type Store = {
    token: string;
    isLogged: boolean;
    loginUser: (jwtToken: string) => void;
    logoutUser: () => void;
};

Please guide me on how to resolve this error.

Upvotes: 2

Views: 16473

Answers (2)

Here an example of how you could do it:

import { create } from 'zustand'
import { devtools } from 'zustand/middleware';

const initState: MainState = {
  email: "",
  shadowPassword: "",
  autoLogin: false,
  userAttributes: {},
};

export const useUserStore = create<MainState & StoreActions>()(
  devtools(
    (set) => ({
      ...initState,
      resetUserStore: () => {set({ ...initState }, false, "resetUserStore")},
      setEmail: (value: string) => set({ email: value }, false, "setEmail"),
      setAutoLogin: (email: string, password: string, autoLogin: boolean) => set({
        email: email,
        shadowPassword: password,
        autoLogin
      }, false, "setAutoLogin"),
      setUserAttributes: (value: {[key: string]: string}) => set({ 
        userAttributes: {...value} 
      }, false, "setUserAttributes"),
    })
  )
);

export type MainState = {
  email: string;
  shadowPassword: string;
  autoLogin: boolean;
  userAttributes: {[key: string]: string};
}

export type StoreActions = {
  resetUserStore: () => void,
  setEmail: (value: string) => void;
  setAutoLogin: (email: string, password: string, autoLogin: boolean) => void;
  setUserAttributes: (value: {[key: string]: string}) => void;
}

Upvotes: 0

Nic Estrada
Nic Estrada

Reputation: 532

Try changing create<Store>(devtools... to create<Store>()(devtools... (Note the extra pair of parentheses)

This is documented on their Readme

Screenshot of documentation

Upvotes: 11

Related Questions