@rogerbf/use-middleware

1.0.1 • Public • Published

use-middleware

const logActionMiddleware = (_, { updateActionLog }) => next => action => {
  updateActionLog(action)
  return next(action)
}

const Counter = () => {
  const [state, _dispatch] = React.useReducer((state, action) => {
    if (action === 'increment') {
      return state + 1
    } else if (action === 'decrement') {
      return state - 1
    } else {
      return state
    }
  }, 0)

  const [actionLog, setActionLog] = React.useState([])

  const updateActionLog = action => setActionLog([...actionLog, action])

  const dispatch = useMiddleware(
    { updateActionLog },
    logActionMiddleware,
    _dispatch,
  )

  return (
    <>
      <h1>Count: {state}</h1>
      <button onClick={() => dispatch('increment')}>+</button>
      <button onClick={() => dispatch('decrement')}>-</button>
      <ol>
        {actionLog.map((action, index) => (
          <li key={index}>{action}</li>
        ))}
      </ol>
    </>
  )
}

Package Sidebar

Install

npm i @rogerbf/use-middleware

Weekly Downloads

1

Version

1.0.1

License

MIT

Unpacked Size

3.2 kB

Total Files

3

Last publish

Collaborators

  • rogerbf