JSPM

  • ESM via JSPM
  • ES Module Entrypoint
  • Export Map
  • Keywords
  • License
  • Repository URL
  • TypeScript Types
  • README
  • Created
  • Published
  • Downloads 8
  • Score
    100M100P100Q47436F
  • License MIT

Define and hook into a typed React Context, assured of a descriptive error message if the value was not provided. Comes equipped with various reducer utilities for React useReducer.

Package Exports

  • define-context

Readme

define context

Define and hook into a typed React Context, assured of a descriptive error message if the value was not provided.

const [SomeContext, useSomeContext] = defineContext<SomeContext>('Some', 'such')

The following will throw:

const Child = () => {
  const { someValue } = useSomeContext()
  return <>{someValue}</>
}
render(<SomeContext.Provider value={null}>
  <Child />
</SomeContext.Provider>) // Error! No such value was provided to SomeContext

New! define reduction

Define key-based reducers before you ever hook into them.

const reduction = defineReduction({
  add({ counter, ...rest }: SomeState, amount: number) {
    return {
      ...rest,
      counter: counter + amount
    }
  },
  rename({ counter, ...rest }, name: string, penalty: number) {
    return {
      ...rest,
      name,
      counter: counter - penalty
    }
  }
})

Initialize the reducer with initial state and pass a strictly typed action key to the dispatcher to dispatch typed arguments to the appropriate action.

const [{name, counter}, dispatcher] = reduction.useReduction({
  name: 'anonymous',
  counter: 0
})
const add = dispatcher('add')
const rename = dispatcher('rename')
return <>
  <button 
    onClick={() => add.dispatch(1)}
  >
    {counter}
  </button>
  <button 
    onClick={() => rename.dispatch('Bond, James', 1)} 
    disabled={counter < 1}
  >
    {name}
  </button>
</>

Newer! modelReducer

Selectively reduce a property model to keywise value updates

const reducedModel = modelReducer<SomeState, 'id'>()
function Component() {
    const [{ counter, name }, dispatcher] = reducedModel.useReducer({
    id: '0',
    name: 'anonymous',
    counter: 0
    })
    const setCounter = dispatcher('counter')
    const setName = dispatcher('name')
    //const setId = dispatcher('id') // 'id' not assignable
    return <>
    <button 
      onClick={() => setCounter.dispatch(1)}
    >
      {counter}
    </button>
    <button 
      onClick={() => setName.dispatch('Bond, James')}
    >
      {name}
    </button>
  </>
}