npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@betafcc/red

v0.1.0

Published

Type safe reducers without boilerplate

Downloads

8

Readme

Red

Type-safe, composable, boilerplateless reducers

Install

npm install --save @betafcc/red

By example

import React, { useReducer } from 'react'
import { render } from 'react-dom'
import { red } from '@betafcc/red'

const inputApp = red
  .withState({ input: '' })
  .handle({ setInput: (state, input: string) => ({ input }) })

const todoApp = inputApp
  .withState({ todos: [] as Array<{ msg: string; done: boolean }> })
  .handle({
    add: (state, msg: string) => ({ input: '', todos: [...s.todos, { msg, done: false }] }),
    complete: (state, id: number) => ({ todos: state.todos.map((e, i) => i !== id ? e : { ...e, done: true }) }),
  })

export const TodoApp = () => {
  const [{ input, todos }, { setInput, add, complete }] = todoApp.useHook(useReducer)
  return <>
    <input value={input} onChange={e => setInput(e.target.value)} />
    <button onClick={_ => add(input)}>add</button>
    {todos.map((e, id) => <li key={id} style={e.done ? { textDecoration: 'line-through' } : {}}>
      {e.msg}<button onClick={_ => complete(id)}>done</button>
    </li>)}
  </>
}

render(<TodoApp />, document.getElementById('root'))

The idea

If every action has this shape:

type ActionType<K extends string, P extends Array<unknown>> = {
  type: K
  payload: P
}

We can automatically provide action creators and strong-typed reducer from simple handlers definitions:

const app = red
  .withState({
    input: '',
    todo: [] as Array<{msg: string, id: number, done: boolean}>
  })
  .handle({
    setInput(state, input: string) {
      return { input }
    },

    addTodo(state, msg: string, id: number) {
      return { todo: [...state.todo, {msg, id, done: false}] }
    },

    completeTodo(state, id: number) {
      return { todo: todo.map(t => t.id !== id ? t : {...t, done: true}) }
    }
  })

const {
  intial, // the initial state
  reducer, // the reducer made by combining the handlers
  actions, // the action creators
} = red

The arguments in the handlers define the payload, and their keys define the 'type', the revealed signature is:

import { StateOf, ActionOf } from '@betafcc/red'

type State = StateOf<typeof red>
// { input: string, todo: Array<{msg: string, id: number, done: boolean}> }

type Action = ActionOf<typeof red>
// { type: 'setInput', payload: [string] } | { type: 'addTodo', payload: [string, number] } | { type: 'completeTodo', payload: [number] }

And you also have action creators that matches the signature:

const { addTodo, completeTodo } = app.actions

addTodo('buy milk', 0) // { type: 'addTodo', payload: ['buy milk', 0] }
completeTodo(0) // { type: 'completeTodo', payload: [number] }

If your prefer to define the actions yourself, you can use ActionType helper and withActions method:

import { ActionType } from '@betafcc/red'

type Action =
  | ActionType<'setInput', [string]>
  | ActionType<'addTodo', [string, number]>
  | ActionType<'completeTodo', [number]>

const app = red
  .withState({ input: '', todo: [] as Array<{msg: string, id: number, done: boolean}>})
  .withActions<Action>({ // annotate here
    setInput(state, input) { // so arguments will have infered type, no need to annotate here
      return {input}
    },

    addTodo(state, msg, id) {
      return {todo: [...state.todo, {msg, id, done: false}]}
    },

    completeTodo(state, id) {
      return {todo: todo.map(t => t.id !== id ? t : {...t, done: true})}
    }
  })

Use it

The simplest way to use is to extract the generated reducer, initial and the actions creators:

const {reducer, initial, actions} = app

const App = () => {
  const [state, dispatch] = React.useReducer(reducer, initial)

  return <>
    {state.count}
    <button onClick={_ => dispatch(actions.increment())}>+</button>
  </>
}

But you can use red.useHook for some extra magic:

const App = () => {
  // the action creators will become dispatchers
  const [state, {increment}] = app.useHook(React.useReducer)

  return <>
    {state.count}
    <button onClick={_ => increment()}>+</button>
  </>
}

Merge

You can use red.merge to combine apps together:

const inputApp = red
  .withState({input: ''})
  .handle({setInput: (s, value: string) => ({input: value})})

const todoApp = red
  .withState({todos: [] as Array<{id: number, done: boolean, msg: string}>})
  .handle({add: (s, msg: string, id: number) => ({todos: [...s.todos, {id, msg, done: false}]}) })

const app = red.merge(inputApp).merge(todoApp)
// same as
const app = inputApp.merge(todoApp)
// same as
const app = red
  .withState({input: ''})
  .handle({setInput: (s, value: string) => ({input: value})})
  .withState({todos: [] as Array<{id: number, done: boolean, msg: string}>})
  .handle({add: (s, msg: string, id: number) => ({todos: [...s.todos, {id, msg, done: false}]}) })

Combine

Or you can combine them by namespacing with red.combine, similar to redux's combineReducers:

const inputApp = red.withState({input: ''}).handle({setInput: (s, input: string) => ({input})})
const counterApp = red.withState({count: 0}).handle({increment: s => ({count: s.count + 1})})

const app = red.combine({
  ui: inputApp,
  counter: counterApp
})

// equivalent to:
const app = red.withState({
  ui: {input: ''},
  counter: {count: 0}
}).handle({
  // note that you have to manually namespace the state
  setInput: (s, input: string) => ({...s, ui: {input}}),
  increment: s => ({...s, counter: {count: s.counter.count + 1}})
})