Flux with actions at center stage. Write optimistic updates, cancel requests, and track changes with ease.
JavaScript CSS HTML Other
Clone or download
Latest commit f68acbc Aug 2, 2018

README.md

Microcosm

CircleCI codecov npm npm

Microcosm is a state management tool for React (and similar libraries). Keep track of user actions, cancel requests, and perform optimistic updates with ease.

What you get

What it looks like

import Microcosm, { get, set } from 'microcosm'
import axios from 'axios'

let repo = new Microcosm()

function getUser (id) {
  // This will return a promise. Microcosm automatically handles promises.
  // See http://code.viget.com/microcosm/api/actions.html
  return axios(`/users/${id}`)
}

// Domains define how a Microcosm should turn actions into new state
repo.addDomain('users', {
  getInitialState () {
    return {}
  },
  addUser (users, record) {
    // The set helper non-destructively assigns keys to an object
    return set(users, record.id, record)
  },
  register () {
    return {
      [getUser]: {
        done: this.addUser
      }
    }
  }
})

// Push an action, a request to perform some kind of work
let action = repo.push(getUser, 2)

action.onDone(function () {
  let user = get(repo.state, ['users', '2'])

  console.log(user) // { id: 2, name: "Bob" }
})

// You could also handle errors in a domain's register method
// by hooking into `getUser.error`
action.onError(function () {
  alert("Something went terribly wrong!")
})

How to get started

Checkout the installation guide, then dive into our quickstart!

Contributing

This project uses yarn workspaces to manage multiple packages from the same repo. Projects include:

Be sure to check out our contributing guide for instructions on getting started.

License

Microcosm and all related packages are licensed under MIT.


Code At Viget

Visit code.viget.com to see more projects from Viget.