Coder Social home page Coder Social logo

restated's Introduction

npm (tag) Travis (.org) branch gzip bundle size NPM

reStated

An ambitiously tiny, gizp ~900b, flux-like progressive state management library inpired by Redux and Vuex.


Features

  • Flux pattern
  • Immutable state
  • Action Mutators
  • Computed state
  • Subscription

Inspired by Redux and Vuex, reStated removes the boilerplate to keep your state simple, intuitive and immutable.

It follows the flux pattern and let you change your state only via Action Mutators.

reStated is framework agnostic, and can work with React, Vuejs etc.

reStated allows you to mutate your state in place without the need for reducers like Redux or actions and mutations like Vuex.

reStated allows you to write computed state, which are functions that select part of your state, to return a new value that will be set in your state.

reStated also provides a subscription method to watch the state


Installation

The best way to import reStated is via ESM JavaScript, where we specify the type as module, and we import it from unpkg.com

Make sure type="module" exists in the script tag.

<script type="module">
  import reStated from '//unpkg.com/restatedjs';
  
  ...
</script>

Or by installing in your project

npm install restatedjs
import reStated from 'restatedjs';

Create the store

reStated({state:{}, ...function ActionMutators})

<script type="module">

import reStated from '//unpkg.com/restatedjs';

const store = reStated({
  state:{
    firstName: '',
    lastName: '',
    count: 0,

    /** Computed state: function that returns a new value to the state **/
    fullName(state) { 
      return `${state.firstName} ${state.lastName}`
    },
  },

  /** Action Mutators: functions to update the state **/

  setFirstName(state, firstName) {
    state.firstName = firstName;
  },
  setLastName(state, lastName) {
    state.lastName = lastName;
  },

  // Async example
  async makeAjaxCall(state, url) {
    state.pending = true; // The state will be mutated
    state.data = await fetch(url);
    state.pending = false; // The state will be mutated
  },

  // Other action mutators
  inc(state) => state.count++,
  dec(state) => state.count--,
});
</script>

State

State are the values that can be initially set, or set via an action mutator.

Initial state can be set during initialization of the store, in the state property.

The state property is an object that may contains: String, Number, Array, Plain Object, Boolean, Null, Undefined.

If the value of a state property is a function it will be converted into a computed state (read more below)

const store = reStated({
  state: {
    name: 'reStated',
    version: '1.x.x',
    firstName: '',
    lastName: '',
    count: 0,
  }
})

Usage

You can access the full state with the method reStated.getState() or by using any state properties.

// get full state object
const myFullState = store.getState();

// or individual property

const name = store.name;
const version = store.version;

Actions Mutators

Action mutators are functions that can mutate the state in place. They accept the current state as the first argument and can also be chained during execution.

Action mutators are set during initialization of the store.

const store = reStated({
  setFirstName(state, firstName) {
    state.firstName = firstName;
  },
  setLastName(state, lastName) {
    state.lastName = lastName;
  },

  // Async example
  async makeAjaxCall(state, url) {
    state.pending = true; // The state will be mutated
    state.data = await fetch(url);
    state.pending = false; // The state will be mutated
  },

  // Other action mutators
  inc(state) => state.count++,
  dec(state) => state.count--,
})

Usage

Run an action mutator by using the function name, and action mutators can also be chained.

store.setFirstName('Mardix');
store.setLastName('M.');

store.inc(); // will increment the count
store.dec(); // will decrement the count

// chainable
store
  .inc()
  .makeAjaxCall()
  .dec();

Computed State

Computed State are function that select part of the state to create new properties. They are function defined along with the initial state. The selected value will be assigned to the function's name

const store = reStated({
  state:{
    firstName: '',
    lastName: '',
    count: 0,

    /** Computed state: function that returns a new value to the state **/
    fullName(state) { 
      return `${state.firstName} ${state.lastName}`
    },
  },
  ...
});

A new property fullName will be assigned to the state and will contain the returned value.

Usage

The same way you would access the initial state, computed states are accessed the same way, by calling the property.

  const fullName = store.fullName;

Subscribe to changes

You can subscribe to changes in the state. Each time the state is updated it will run a function that you set.

reStated.subscription(listener:function)

const sub = store.subscribe(state => {
  console.log(`I'm updated ${state.count}`);
});

Unsubscribe to changes

To unsubscribe

const unsub = store.subscribe(state => {
  console.log(`I'm updated ${state.count}`);
});

// This will unsubscribe
unsub();

API

reStated()

reStated.getState()

reStated.subscribe()


LICENSE: MIT

(c) 2019 Mardix

restated's People

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.