zustand-stateful-getter
TypeScript icon, indicating that this package has built-in type declarations

1.0.2 • Public • Published

zustand-stateful-getter

Leave zustand object getter alive.

Installation

npm install zustand-stateful-getter

zustand@^4.3.7 is peer dependency.

Usage

Provides a near-complete transparent API.

import { createStore } from 'zustand/vanilla'
import { statefulGetter } from 'zustand-stateful-getter'

const nameStore = createStore(
  statefulGetter(
    (set) => ({
      firstName: 'John',
      lastName: 'Doe',
      get fullName() {
        return `${this.firstName} ${this.lastName}`
      },
      setFirstName: (firstName) => set({ firstName }),
      setLastName: (lastName) => set({ lastName }),
    })
  )
)

pizzaStore.getState().fullName // 'John Doe'
pizzaStore.getState().setFirstName('Jane')
pizzaStore.getState().fullName // 'Jane Doe'

Why?

See https://github.com/pmndrs/zustand/issues/132

import { createStore } from 'zustand/vanilla'

const nameStore = createStore(
  (set) => ({
    firstName: 'John',
    lastName: 'Doe',
    get fullName() {
      return `${this.firstName} ${this.lastName}`
    },
    setFirstName: (firstName) => set({ firstName }),
    setLastName: (lastName) => set({ lastName }),
  })
)

pizzaStore.getState().fullName // 'John Doe'
pizzaStore.getState().setFirstName('Jane')
pizzaStore.getState().fullName // 'John Doe', not 'Jane Doe'

The fullName getter is not updated after setFirstName is called. This is because the getter is not a part of the state, and the state is not updated. zustand-statuful-getter solves this problem by Proxy trap.

With subscribe API and the subscriptionsWithSelector middleware could be a solution, but the desire to write store layouts declaratively led to the creation of this middleware.

Disclaimer

It is recommended that the getter body be written without conditionals. See https://github.com/sungchuni/detective-getter-deps#disclaimer

It relies heavily on the Proxy class, so you couldn't use it with versions of the JavaScript engine that don't have a Proxy implementation. Always consult the "Can I use Proxy?".

Readme

Keywords

Package Sidebar

Install

npm i zustand-stateful-getter

Weekly Downloads

2

Version

1.0.2

License

Apache-2.0

Unpacked Size

27.8 kB

Total Files

20

Last publish

Collaborators

  • sungchuni