Skip to content

TypeScript example of optional middleware in zustand v4 #1266

Closed Answered by devanshj
dasblitz asked this question in Q&A
Discussion options

You must be logged in to vote

How about just this...

import create from 'zustand'
import { devtools, persist } from 'zustand/middleware'

const envAwareDevtools = 
  ( process.env.NODE_ENV === "production"
      ? f => f
      : devtools
  ) as typeof devtools

interface BearState {
  bears: number
  increase: (by: number) => void
}

const useBearStore = create<BearState>()(
  envAwareDevtools(
    persist((set) => ({
      bears: 0,
      increase: (by) => set((state) => ({ bears: state.bears + by })),
    }))
  )
)

Now instead of writing devtools you can just write envAwareDevtools instead of doing the unnecessary hassle to type the middleware and createWithMiddleware in the original code. Let me know if this doesn'…

Replies: 2 comments 2 replies

Comment options

You must be logged in to vote
0 replies
Comment options

You must be logged in to vote
2 replies
@dasblitz
Comment options

@devanshj
Comment options

Answer selected by dasblitz
# for free to join this conversation on GitHub. Already have an account? # to comment
Category
Q&A
Labels
None yet
3 participants