1.1.1 • Published 6 years ago

update-creator v1.1.1

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

Update creator

Create an update function to pass messages to child components.

This idea is inspired by TEA (The Elm Architecture).

The library is originally designed to work with React components. But technically, it's applicable to any UI libraries/frameworks

Install

npm install --save update-creator

Usage

Create a child component Child.js

const Child = ({ onClick, onSubmit, onChange }) => {
  return (
    <div>
      <button onClick={onClick}>Cancel</button>
      <input onChange={onChange} name="title" />
      <button onClick={() => onSubmit({ title: 'foo bar' })}>Submit</button>
    </div>
  )
}
export default Child

Create constants for reusable messages Constants.js

export const MSG = {
  CLICK: 'ON_CLICK',
  SUBMIT: 'ON_SUBMIT',
  CHANGE: 'ON_CHANGE'
}

Create the parent component

import React from 'react'
import updateCreator from 'update-creator'

import Child from './Child'
import { MSG } from './Constants'

const { CLICK, SUBMIT, CHANGE } = MSG
const parentMessages = [
  CLICK,
  SUBMIT,
  CHANGE
]

class Parent extends React.Component {
  update = updateCreator({
    [CLICK]: () => {
      console.log('on click')
    },
    [SUBMIT]: (values) => {
      console.log('values', values)
    },
    [CHANGE]: (event) => {
      console.log('current value', event.target.value)
    }
  }, parentMessages)

  render() {
    return (
      <Child
        onClick={this.update(CLICK)}
        onSubmit={this.update(SUBMIT)}
        onChange={this.update(CHANGE)}
      />
    )
  }
}

API Reference

updateCreator(actions, messages = [])

  • actions is a required object that contains event handlers, follow this pattern [message]: eventHandler
  • messages is an optional array of messages. However, it's recommended to specify it so the library can detect whether the update function covers all possibilities

License

MIT

1.1.1

6 years ago

1.1.0

6 years ago

1.0.0

6 years ago