Vanilla JavaScript port of the popular ClojureScript library for pragmatic, flux-like state management. I highly recommend checking out re-frame's original documentation to learn about its philosophy, terminology, and patterns. All design credit goes to the original authors โ thank you for the inspiration.
Re-frame helps make state management predictable, testable, and pragmatic. It achieves this via message passing, which decouples action from intent. On top of this, it provides first-class semantics for dealing with side-effects, as these are unavoidable in real-world applications.
From a high-level, re-frame is flux-like with events and event handlers, which are similar to redux's actions and reducers. Compared to redux, re-frame is more feature complete out of the box, with built-in interceptors, effects, subscriptions, and test utilties. You'll find that you can be productive without needing to reach for third-party middleware.
The quickest way to get started is by installing @re-frame/standalone
, which bundles everything you'll need to build a typical application: a store to manage state, subscriptions to query it, effects such as http, orchestrate, and more since the real world is more complicated than TodoMVC.
yarn add @re-frame/standalone
Once you've become familiar with re-frame, feel free to install only the packages you need to cut down on install size. You'll need @re-frame/store to create a store, but everything else is optional.
Package | Description |
---|---|
@re-frame/store | Creates a re-frame store (ergonomic API over @re-frame/core) |
@re-frame/core | Low-level store API |
@re-frame/effects | Useful effects for most web apps (HTTP, orchestrate, etc.) |
@re-frame/interceptors | Common interceptors (path, immer, debug, etc.) |
@re-frame/react | React bindings (useDispatch, useSubscription) |
@re-frame/preact | Preact bindings (useDispatch, useSubscription) |
@re-frame/global | A global re-frame store instance |
Below is an example that shows how to create a store, define event handlers, setup and access subscriptions, and run side effects. For now, you should refer to the original re-frame documentation for best practices.
Unlike the original re-frame library which uses a singleton store, the JavaScript package provides an API for creating your own independent stores. If you want the convenience of a global store, use @re-frame/global.
import {createStore} from "@re-frame/store"
const store = createStore()
A store holds application state in an object called "db" (it's your in-memory database). To make updates to the db, you register and dispatch events:
// Define event handlers:
store.event("init", (db, event) => ({count: 0}))
store.event("increment", (db, event) => ({count: db.count + 1}))
// Send events to the store:
store.dispatch("init") // db = { count: 0 }
store.dispatch("increment") // db = { count: 1 }
store.dispatch("increment") // db = { count: 2 }
// Pass data with events:
store.event("add", (db, { amount }) => ({ count: db.count + amount }))
store.dispatch("add", { amount: 5 })
To access the db, register queries with the store. All active queries are recomputed every time the db changes, and are only recomputed once per change regardless of how many subscribers exist.
store.computed("count", db => db.count)
const count = store.subscribe("count")
store.dispatchSync("init") // db = { count: 0 }
count.deref() // 0
store.dispatchSync("increment") // db = { count: 1 }
count.deref() // 1
// You can also watch a subscription to see all changes over time:
count.watch(value => { ... })
// Cleanup your subscription when you're done with it.
count.dispose()
// You can also pass parameters to the query:
store.computed("todos", (db, { completed }) => {
return db.todos.filter(todo => todo.completed === completed)
})
store.subscribe("todos", { completed: false })
Most events will simply update the store's state. This update is one particular type of effect that events can have (appropriately called the "db" effect"), and while most events will only update the db, you can step up a level and trigger any number of effects.
import {http} from "@re-frame/effects"
// Register your effect with the store:
store.effect("http", http)
// Define an event handler that will trigger that effect:
store.event.fx("load-data", (ctx, event) => ({
// Updates your store state ("db")
db: {
...ctx.db,
loadingData: true,
},
// Also triggers an "http" effect to make a network request.
http: {
url: "my.api.com/endpoint",
method: "GET",
success: "load-data-success",
failure: "load-data-failure",
},
}))
// Initiate the effect:
store.dispatch("load-data")
@re-frame's API provides the same conceptual ideas as the original re-frame library, with a few name changes to make them more compact and palatable to developers that are used to mobx and redux:
@re-frame/store API | Clojure re-frame API |
---|---|
store.event("id", handler) |
(re-frame/reg-event-db :id handler) |
store.event.fx("id", handler) |
(re-frame/reg-event-fx :id handler) |
store.effect("id", handler) |
(re-frame/reg-fx :id handler) |
store.computed("id", handler) |
(re-frame/reg-sub :id handler) |
store.subscribe("id", params) |
(re-frame/subscribe [:id arg]) |
store.dispatch("id", payload) |
(re-frame/dispatch [:id arg]) |
Low-level store API:
@re-frame/core API | Clojure re-frame API |
---|---|
store.registerEventDB("id", handler) |
(re-frame/reg-event-db :id handler) |
store.registerEventFX("id", handler) |
(re-frame/reg-event-fx :id handler) |
store.registerEffect("id", handler) |
(re-frame/reg-fx :id handler) |
store.registerSubscription("id", handler) |
(re-frame/reg-sub :id handler) |
store.subscribe({ id, arg }) |
(re-frame/subscribe [:id arg]) |
store.dispatch({ id, arg }) |
(re-frame/dispatch [:id arg]) |
IE / Edge |
Firefox |
Chrome |
Safari |
---|---|---|---|
IE11, Edge | last 2 versions | last 2 versions | last 2 versions |
The MIT License (MIT)
Copyright (c) 2018 David Zukowski
Copyright (c) 2015-2017 Michael Thompson
Copyright (c) 2017 Evgeny Poberezkin
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
re-frame's People
re-frame's Issues
Subscriptions run en masse when inactive tab becomes active
Need to confirm affected browsers. Subscription updates are behind a raf, which is the source of the issue. State updates occur as expected. Solution is likely to pause subscriptions while tab is inactive and run a single update once tab becomes active again.
Consider more ergonomic API
Our API originally mirrored re-frame's quite closely:
store.registerEventDB()
store.registerEventFX()
store.registerEffect()
store.registerSubscription()
This was later condensed to:
store.event()
store.event.fx()
store.effect()
store.computed()
I'm not entirely convinced these changes are worth it, although they did receive positive feedback from some beta users. I'd also like to reconsider how events are dispatched, since dispatch([id, ...args])
is not idiomatic JavaScript โ a traditional object, or variadic arguments, may be more palatable.
Reconsider global interceptor API
Node support
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
๐ Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
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.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google โค๏ธ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.