Git Product home page Git Product logo

undux's Introduction

undux

Build Status npm mit

Dead simple state management for React

Install

# Using Yarn:
yarn add undux

# Or, using NPM:
npm install undux --save

Design Goals

  1. Complete type-safety, no exceptions
  2. Super easy to use: forget actions, reducers, dispatchers, containers, etc.
  3. Familiar abstractions: just get and set

Read more here

Use

1. Create a store

import { connect, createStore } from 'undux'

// If you're using Undux with TypeScript, declare your store's types.
type Store = {
  today: Date
  users: string[]
}

// Create a store with an initial value.
let store = createStore<Store>({
  today: new Date,
  users: []
})

export let withStore = connect(store)

Be sure to define a key for each value in your model, even if the value is initially undefined.

2. Connect your React components

import { withStore } from './store'

// Update the component when `today` changes
let MyComponent = withStore('today')(({ store }) =>
  <div>
    Hello! Today is {store.get('today')}
    <button onClick={() => store.set('today')(new Date)}>Update Date</button>
  </div>
)

That's all there is to it.

Features

Effects

Though Undux automatically updates your model for you, it also lets you listen on and react to model updates (similarly to how vanilla Redux lets you subscribe to Actions). Undux subscriptions are full Rx observables, so you have fine control over how you react to a change:

store
  .on('today')
  .filter(_ => _.getTime() % 2 === 0) // only even timestamps
  .debounce(100)
  .subscribe(_ => console.log('Date changed', _))

You can even use Effects to trigger a change in response to an update:

store
  .on('today')
  .debounce(100)
  .subscribe(async date => {
    let users = await api.get({ since: date })
    store.set('users')(users)
  })

Lensed connects

Instead of updating your React component when anything on the model changed, with Undux you subscribe just to specific properties on your model. Notice how in our React example we only update when today changes:

let MyComponent = withStore('today')(
  ({ store }) => ...
)

To make your component re-render when a property changed, just pass it to withStore as a string.

Partial application all the way through

Partially apply the connect function to yield a convenient withStore function:

let withStore = connect(store)

Or, partially apply the set function to yield a convenient setter:

let setUsers = store.set('users')
setUsers(['amy'])
setUsers(['amy', 'bob'])

Built-in logger

If you create your store with withLogger higher order store, all model updates (which key was updated, previous value, and new value) will be logged to the console.

To enable the logger, simply import withLogger and wrap your store with it:

import { createStore, withLogger } from 'undux'

let store = withLogger(createStore<Store>({...}, true))

The logger will produce logs that look like this:

Plugins

Undux is easy to modify with plugins (also called "higher order stores"). Just define a function that takes a store as an argument and returns a store, adding listeners along the way. For convenience, Undux supports 2 types of listeners for plugins:

import { createStore, Plugin } from 'undux'

let withLocalStorage: Plugin = store => {

  // Listen on an event
  store.onAll().subscribe(_ =>
    console.log('something changed!', _)
  )

  // Listen on an event (fires before the model is updated)
  store.beforeAll().subscribe(({ key, previousValue, value }) =>
    localStorage.set(key, value)
  )

}

Undux also supports .on() and .before(), but because a plugin doesn't know what Actions will be bound to it, these are generally unsafe to use.

Recipes

Creating a store

import { connect, createStore, Store } from 'undux'

type MyStore = {
  foo: number
  bar: string[]
}

let store = createStore<MyStore>({
  foo: 12,
  bar: []
})

export type StoreProps = {
  store: Store<MyStore>
}

export let withStore = connect(store)

Stateless component with props

Have your own props? No problem.

import { withStore } from './store'

type Props = {
  foo: number
}

let MyComponent = withStore('today')<Props>(({ foo, store }) =>
  <div>
    Today is {store.get('today')}
    Foo is {foo}
  </div>
)

<MyComponent foo={3} />

Stateful component with props

Undux is as easy to use with stateful components as with stateless ones.

import { StoreProps, withStore } from './store'

type Props = {
  foo: number
}

let MyComponent = withStore('today')(class extends React.Component<StoreProps & Props>{
  render() {
    <div>
      Today is {this.props.store.get('today')}
      Foo is {this.props.foo}
    </div>
  }
})

<MyComponent foo={3} />

Design philosophy

Goal #1 is total type-safety.

Getting, setting, reading, and listening on model updates is 100% type-safe: use a key that isn't defined in your model or set a key to the wrong type, and you'll get a compile-time error. And connected components are just as type-safe.

Goal #2 is letting you write as little boilerplate as possible.

Undux is like Redux, but reducers are already baked-in. Undux automatically creates an action and a reducer for each key on your state, so you don't have to write tedious boilerplate. Undux still emits Actions under the hood (which you can listen on to produce effects), but gives you an incredibly simple get/set API that covers most use cases.

If you're using Undux with the provided React connector, Undux will update your React component any time a reducer fires (just like React-Redux). You can optionally filter on specific state keys that you care about for more targeted updates.

Goal #3 is familiar abstractions.

No need to learn about Actions, Reducers, or any of that. Just call get and set, and everything works just as you expect.

More examples

Tests

yarn test

License

MIT

undux's People

Contributors

bcherny avatar

Watchers

 avatar  avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.