immex
TypeScript icon, indicating that this package has built-in type declarations

0.2.5 • Public • Published

Immex

  • based on immer.js
  • (global) statement management
  • react hooks friendly
  • insanely easy to use, just one API
  • support async/await reducers

Example

See examples here, or

Open in Gitpod

Installation

npm install --save immex immer

Usage

Define your store/reducer and export the react hook

// useCalculator.js
import immex from 'immex'

// immer reducer function
// refer: https://immerjs.github.io/immer/docs/curried-produce
const calculator = (draft, {operator, payload}) => {
  switch (operator) {
    case 'add':
      draft.value += payload
      break
    case 'sub':
      draft.value -= payload
      break
    default:
  }
}

const useCalculator = immex(
  calculator,
  {value: 0} // initial state
)
export default useCalculator

Use the exported react hook in function components, any change to the state will be updated in all components automatically

// foo.tsx
import React from 'react'
import useCalculator from './useCalculator'

export default () => {
  const [{value}, dispatch] = useCalculator()
  return (
    <>
      <div>
        <span>Foo:</span>
        {value}
      </div>
      <div>
        <button onClick={() => dispatch({ operator: "add", payload: 1 })}>+</button>
        <button onClick={() => dispatch({ operator: "sub", payload: 1})}>-</button>
      </div>
    </>
  )
}

Another component

// bar.tsx
import React from 'react'
import useCalculator from './useCalculator'

export default () => {
  const [{value}] = useCalculator()
  // this value keeps update to the one in component foo
  return (
    <div>
      <span>Bar:</span>
      {value}
    </div>
  )
}

Readme

Keywords

Package Sidebar

Install

npm i immex

Weekly Downloads

0

Version

0.2.5

License

MIT

Unpacked Size

36 kB

Total Files

13

Last publish

Collaborators

  • yewei