Giter Site home page Giter Site logo

rdadoune / satcheljs Goto Github PK

View Code? Open in Web Editor NEW

This project forked from microsoft/satcheljs

0.0 1.0 0.0 1.04 MB

Satchel is a data store based on the Flux architecture. It is characterized by exposing an observable state that makes view updates painless and efficient.

Home Page: https://microsoft.github.io/satcheljs

License: Other

JavaScript 0.72% TypeScript 99.28%

satcheljs's Introduction

Satchel

Satchel is a dataflow framework based on the Flux architecture. It is characterized by exposing an observable state that makes view updates painless and efficient.

Build Status

Influences

Satchel is an attempt to synthesize the best of several dataflow patterns typically used to drive a React-based UI. In particular:

  • Flux is not a library itself, but is a dataflow pattern conceived for use with React. In Flux, dataflow is unidirectional, and the only way to modify state is by dispatching actions through a central dispatcher.
  • Redux is an implementation of Flux that consolidates stores into a single state tree and attempts to simplify state changes by making all mutations via pure functions called reducers. Ultimately, however, we found reducers and immutable state cumbersome to deal with, particularly in a large, interconnected app.
  • MobX provides a seamless way to make state observable, and allows React to listen to state changes and rerender in a very performant way. Satchel uses MobX under the covers to allow React components to observe the data they depend on.

Advantages

There are a number of advantages to using Satchel to maintain your application state:

  • Satchel enables a very performant UI, only rerendering the minimal amount necessary. MobX makes UI updates very efficient by automatically detecting specifically what components need to rerender for a given state change.
  • Satchel's datastore allows for isomorphic JavaScript by making it feasible to render on the server and then serialize and pass the application state down to the client.
  • Satchel supports middleware that can act on each action that is dispatched. (For example, for tracing or performance instrumentation.)
  • Satchel is type-safe out of the box, without any extra effort on the consumer's part.

Installation

Install via NPM:

npm install satcheljs --save

In order to use Satchel with React, you'll also need MobX and the MobX React bindings:

npm install mobx --save

npm install mobx-react --save

Usage

The following examples assume you're developing in Typescript.

Create a store with some initial state

import { createStore } from 'satcheljs';

let getStore = createStore(
    'todoStore',
    { todos: [] }
);

Create a component that consumes your state

Notice the @observer decorator on the component—this is what tells MobX to rerender the component whenever the data it relies on changes.

import { observer } from 'mobx-react';

@observer
class TodoListComponent extends React.Component<any, any> {
    render() {
        return (
            <div>
                getStore().todos.map(todo => <div>{todo.text}</div>)
            </div>
        );
    }
}

Implement an action creator

import { actionCreator } from 'satcheljs';

let addTodo = actionCreator(
    'ADD_TODO',
    (text: string) => ({ text: text })
);

Implement a mutator

You specify what action a mutator subscribes to by providing the corresponding action creator. If you're using TypeScript, the type of actionMessage is automatically inferred.

import { mutator } from 'satcheljs';

mutator(addTodo, (actionMessage) => {
    getStore().todos.push({
        id: Math.random(),
        text: actionMessage.text
    });
};

Create and dispatch an action

import { dispatch } from 'satcheljs';

dispatch(addTodo('Take out trash'));

Bound action creators

Bound action creators create and dispatch the action in one call.

import { boundActionCreator } from 'satcheljs';

let addTodo = boundActionCreator(
    'ADD_TODO',
    (text: string) => ({ text: text })
);

// This creates and dispatches an ADD_TODO action
addTodo('Take out trash');

Orchestrators

Orchestrators are like mutators—they subscribe to actions—but they serve a different purpose. While mutators modify the store, orchestrators are responsible for side effects. Side effects might include making a server call or even dispatching further actions.

The following example shows how an orchestrator can persist a value to a server before updating the store.

import { boundActionCreator, orchestrator } from 'satcheljs';

let requestAddTodo = boundActionCreator(
    'REQUEST_ADD_TODO',
    (text: string) => ({ text: text })
);

orchestrator(requestAddTodo, async (actionMessage) => {
    await addTodoOnServer(actionMessage.text);
    addTodo(actionMessage.text);
};

Simple mutators and orchestrators

In many cases a given action only needs to be handled by one mutator or orchestrator. Satchel provides the concept of simple subscribers which encapsulate action creation, dispatch, and handling in one simple function call.

The addTodo mutator above could be implemented as follows:

let addTodo = simpleMutator(
    'ADD_TODO',
    function addTodo(text: string) {
        getStore().todos.push({
            id: Math.random(),
            text: actionMessage.text
        });
    });

Simple orchestrators can be created similarly:

let requestAddTodo = simpleOrchestrator(
    'REQUEST_ADD_TODO',
    async function requestAddTodo(text: string) {
        await addTodoOnServer(actionMessage.text);
        addTodo(actionMessage.text);
    });

These simple mutators and orchestrators are succinct and easy to write, but they come with a restriction: the action creator is not exposed, so no other mutators or orchestrators can subscribe to it. If an action needs multiple handlers then it must use the full pattern with action creators and handlers implemented separately.

License - MIT

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.