Skip to content

Typescript + Immer + Slice pattern #1796

Answered by dbritto-dev
u-rogel asked this question in Q&A
Discussion options

You must be logged in to vote

@u-rogel here you go https://codesandbox.io/s/zustand-updating-draft-states-and-slice-pattern-basic-demo-3e9zby?file=/src/App.tsx

For immer + Slice Pattern you need to create the next type helper

type ImmerStateCreator<T> = StateCreator<
  T,
  [["zustand/immer", never], never],
  [],
  T
>;

then you can use it like this

const createBearSlice: ImmerStateCreator<BearSlice> = (set) => ({
  bears: 0,
  add: () => set(
    (state) => {
      state.bears += 1
    }
  ),
})

I created a codesandbox example with the code that you need to achieve what you want (immer + slice pattern). BTW, I'll update the immer guide to include it.

Note: you shouldn't prefix your slice creators with use they're j…

Replies: 4 comments 15 replies

Comment options

You must be logged in to vote
1 reply
@u-rogel
Comment options

Comment options

You must be logged in to vote
8 replies
@dbritto-dev
Comment options

@u-rogel
Comment options

@u-rogel
Comment options

@dbritto-dev
Comment options

@oravecz
Comment options

Answer selected by u-rogel
Comment options

You must be logged in to vote
6 replies
@tcoopman
Comment options

@dbritto-dev
Comment options

@tcoopman
Comment options

@sirmong
Comment options

@dbritto-dev
Comment options

Comment options

You must be logged in to vote
0 replies
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
7 participants