1.0.1 • Published 4 years ago

@rogerbf/use-middleware v1.0.1

Weekly downloads
2
License
MIT
Repository
github
Last release
4 years ago

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>
    </>
  )
}