Microcosm is a state management tool for React (and similar libraries). Keep track of user actions, cancel requests, and perform optimistic updates with ease.
- A central place to track all application data
- Schedule work with actions
- Actions understand Promises out of the box and move through predefined states.
- Keep loading states out of the data layer. Track action progress using status callbacks.
- Split up application state in large apps while still sharing common data
- Painless optimistic updates
- Track changes and handle business logic with Presenter components
- 5.5kb gzipped (~18kb minified)
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!")
})
Checkout the installation guide, then dive into our quickstart!
This project uses Lerna, a way to manage multiple JavaScript projects in the same repo. Projects include:
- microcosm - The core project
- microcosm-preact - Preact bindings
- microcosm-devtools - Developer tools
- microcosm-graphql - Experimental GraphQL support
- microcosm-react-router - Experimental ReactRouter support
- microcosm-www - The website
- microcosm-www-next - Ongoing work on the next website
Be sure to check out our contributing guide for instructions on getting started.
Visit code.viget.com to see more projects from Viget.