Skip to content

How can I use subscribeWithSelector with createStore? #2464

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

You must be logged in to vote

@ritvij14 @AshotN here you go:

Let's modify the example from nextjs guide:

export const createCounterStore = (
  initState: CounterState = defaultInitState
) => {
  return createStore<CounterStore>()(
    subscribeWithSelector((set) => ({
      ...initState,
      decrementCount: () => set((state) => ({ count: state.count - 1 })),
      incrementCount: () => set((state) => ({ count: state.count + 1 })),
    }))
  )
}
export const useCounterStore = <T,>(
  selector: (store: CounterStore) => T,
): [T, CounterStoreApi] => {
  const counterStoreContext = useContext(CounterStoreContext)

  if (!counterStoreContext) {
    throw new Error(`useCounterStore must be used within CounterStoreProvider`)

Replies: 1 comment 2 replies

Comment options

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

Answer selected by dbritto-dev
@AshotN
Comment options

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
3 participants