• Stars
    star
    123
  • Rank 289,035 (Top 6 %)
  • Language
    JavaScript
  • Created almost 7 years ago
  • Updated over 6 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Redux statecharts

Redux Statechart

To use this please check out my article https://medium.freecodecamp.org/how-to-model-the-behavior-of-redux-apps-using-statecharts-5e342aad8f66 and the xstate project: https://github.com/davidkpiano/xstate

Install

Create your statechart JSON

const statechart = {
  initial: 'Init',
  states: {
    Init: {
      on: { CLICKED_PLUS: 'Init.Increment' },
      states: {
        Increment: {
          onEntry: INCREMENT
        }
      }
    }
  }
}

Install xstate

Install xstate yarn add xstate and create the machine object

import { Machine } from 'xstate' // yarn add xstate

const machine = Machine(statechart)

The Redux middleware

const UPDATE = '@@statechart/UPDATE'

export const statechartMiddleware = store => next => (action) => {
  const state = store.getState()
  const currentStatechart = state.statechart // this has to match the location where you mount your reducer

  const nextMachine = machine.transition(currentStatechart, action)

  const result = next(action)

  // run actions
  nextMachine.actions.forEach(actionType =>
    store.dispatch({ type: actionType, payload: action.payload }))

  // save current statechart
  if (nextMachine && action.type !== UPDATE) {
    if (nextMachine.history !== undefined) {
      // if there's a history, it means a transition happened
      store.dispatch({ type: UPDATE, payload: nextMachine.value })
    }
  }

  return result
}

Reducer

export function statechartReducer(state = machine.initialState, action) {
  if (action.type === UPDATE) {
    return action.payload
  }
  return state
}

Finally put everything together

const rootReducer = combineReducers({
  statechart: statechartReducer
})

const store = createStore(
  rootReducer,
  applyMiddleware(
    statechartMiddleware,
  ),
)

// make sure your initial state actions are called
machine.initialState.actions.forEach(actionType =>
  store.dispatch({ type: actionType }))

Best practices

Folder structure

It makes sense to separate your states into specific folders, and have each folder contain the reducers, epics, constants, selectors and containers pertaining that specific state. Turns out statechart not only are a great tool to model behavior, but also to organize our apps in a filesystem! Since a statechart is hierarchical, this follows perfectly the filesystem structure.

For instance, imagine this statechart example:

{
  initial: 'Init',
  states: {
    Init: {
      on: {
        FETCH_DATA_CLICKED: 'FetchingData',
      },
      initial: 'NoData',
      states: {
        ShowData: {},
        Error: {},
        NoData: {}
      }
    },
    FetchingData: {
      on: {
        FETCH_DATA_SUCCESS: 'Init.ShowData',
        FETCH_DATA_FAILURE: 'Init.Error',
        CLICKED_CANCEL: 'Init.NoData',
      },
      onEntry: 'FETCH_DATA_REQUEST',
      onExit: 'FETCH_DATA_CANCEL',
    },
  }
}

One can imagine separating this JSON into several files:

β”œβ”€β”€ FetchingData.js
β”œβ”€β”€ Init
β”‚Β Β  β”œβ”€β”€ Error.js
β”‚Β Β  β”œβ”€β”€ NoData.js
β”‚Β Β  β”œβ”€β”€ ShowData.js
β”‚Β Β  └── index.js
└── index.js

Notice that states without any substate can just be files, and that there's always an index.js within each folder.

If we explore the contents of the main root index.js we can see that it's the starting point for the statechart:

import Init from './Init'
import FetchingData from './FetchingData'

export default {
  initial: 'Init',
  states: {
    ...Init,
    ...FetchinData,
  }
}

Furthemore we can also contain our redux logic within these folders/files:

import Init, {
  reducer as initReducer,
  epic as initEpic,
} from './Init'

import FetchingData, {
  reducer as fetchinDataReducer,
  epic as fetchingDataEpic,
} from './FetchingData'

export const rootEpic = combineEpics(
  initEpic,
  fetchingDataEpic
)

export const rootReducer = combineReducers({
  init: initReducer,
  data: fetchingDataReducer
})

export default {
  initial: 'Init',
  states: {
    ...Init,
    ...FetchinData,
  }
}

More Repositories

1

torrent-net

Distributed search engines using BitTorrent and SQLite
C
1,013
star
2

peer-tweet

Decentralized feeds using BitTorrent's DHT. Idea from Arvid and The_8472 "DHT RSS feeds" http://libtorrent.org/dht_rss.html
JavaScript
880
star
3

next-13-layout-transitions

TypeScript
161
star
4

apejs

A tiny JavaScript web framework targeted for Google App Engine
JavaScript
152
star
5

hckr.it

Hacker News clone for CouchDB
JavaScript
99
star
6

node-trello

Node wrapper for Trello's HTTP API.
JavaScript
98
star
7

redux-tdd

Redux TDD: Dot-chaining syntax for doing TDD with redux by composing unit tests as if they were integration tests
JavaScript
94
star
8

dmt

Decentralized Mutable Torrents reference implementation
JavaScript
75
star
9

behavioral

Behavioral Programming for JavaScript
JavaScript
73
star
10

react-behavioral

#BehavioralProgramming for React
JavaScript
55
star
11

ldstatic

Host your Linked Data for free, as static pages, using a variety of providers (GitHub Pages, Google Code, Google Drive, etc.), and run SPARQL queries using a basic Linked Data Fragment client.
JavaScript
18
star
12

void-graph

VoID Linked Data graph diagram displayed using JavaScript and SVG
JavaScript
17
star
13

access2couch

A command-line utility for Windows, that pushes a MS Access database to a CouchDB instance. Written in Node.js
JavaScript
10
star
14

waku-page-transitions

Framer motion page transitions with Waku React Server Components
TypeScript
7
star
15

restpark

Minimal RESTful API for querying RDF triples
CSS
7
star
16

redux-behavioral

Behavioral Programming for Redux
JavaScript
6
star
17

behavioral-programming-talk

Behavioral Programming talk at ReactJS day #BehavioralProgramming
5
star
18

jquery-report

Allows you to visualize an HTML Table out of JSON
JavaScript
5
star
19

bitcoin-notify

Notify when new places accepting Bitcoin have been added to OpenStreetMap
JavaScript
4
star
20

blogger-skeleton

Having troubles with creating Blogger themes? I created this skeleton to get you started.
4
star
21

genebanks

Genebanks Linked Data!
JavaScript
3
star
22

seed-couchapp

Couchapp for http://seeds.iriscouch.com/
JavaScript
2
star
23

grinfo-tumblr

A tumblr theme based on Twitter Bootstrap
2
star
24

middleend

some middleend!
PHP
2
star
25

smark

Create beautiful presentation slides with Markdown
JavaScript
2
star
26

seed-scraper

scrape genebanks websites for accession data
JavaScript
2
star
27

linked-data-node

A Linked Data frontend for SPARQL endpoints written in Node.js
JavaScript
2
star
28

romajs

JavaScript User Group & Meetup Roma -> https://plus.google.com/communities/114324393897443067092
JavaScript
2
star
29

json-compressor

Removes whitespace and JavaScript-style comments from a JSON string.
JavaScript
1
star
30

mealo

this is personal stuff! leave now!
JavaScript
1
star
31

kudos

something interesting p2p
JavaScript
1
star
32

ascetica-ines

PHP
1
star
33

resume

my resume :)
CSS
1
star
34

bttrkr

JavaScript
1
star
35

slides

My slides
TeX
1
star
36

human

A little irc bot that loads some data
JavaScript
1
star
37

seedhub

a seedhub is a seedhub no?
JavaScript
1
star
38

grinfo.net

Site for bio-informatics
JavaScript
1
star
39

mustache-rdf

Mustache RDF. Templating for RDF
1
star
40

romapingpong

Rome ping pong
JavaScript
1
star
41

finland-talk

https://lmatteis.github.io/finland-talk
1
star
42

selectjs-api

Documentation for the selectjs.com api
1
star
43

human-chiglug

Couchapp for http://chiglug.tk that shows data generated by the *human* bot
JavaScript
1
star
44

milu

An italian cooking site
JavaScript
1
star
45

waku-infinite-scroll

TypeScript
1
star