Skip to content

Instantly share code, notes, and snippets.

@hyb175
Created August 3, 2016 21:30
Show Gist options
  • Save hyb175/074bf9bc8dc783f301afb4496a68cc95 to your computer and use it in GitHub Desktop.
Save hyb175/074bf9bc8dc783f301afb4496a68cc95 to your computer and use it in GitHub Desktop.
ForwardJS Conference Workshop.

Flux has a lot different concerns and not easily approachable by smaller projects.

Module 1: Redux

  • manages state changes via pure functions and a uni-directional data flow
  • ispired by the Elm Architecture
  • Remove business logic out of React View.

Redux is not a complete architecture

  • Redux does not have async out of the box
    • redux-thunk: it is weird to dispatch function

Redux middleware

  • a third-party extension point between dispatching an action and the moment it reaches the reducer
  • Uses curring to allow you to create custom dispatch functions(middleware) that are called sequentially in between dispatching and the reducer

Three states of any async operation

  • Pending: Operation is in progress. Useful for telling the user to stand by or to keep other requests in sync
  • Fulfilled: Operation is finieshed. Update the UI or other operation
  • Rejected: Operation failed. Handle the failure in whatever way makes sense for your app

Redux Thunk

  • Normal actionsa re objects.
  • Redux-thunk allows you to dispatch a function which will be called by redux-thunk middleware
  • Redux-thunk will pass in dispatcher and getState functions so you can dispatch an action

Pros

  • very simple abstraction. You can write this yourself without the need of a library
  • Fairly easy to test if you run you test
  • good for small one

Cons

  • No real dependency injection that isn't clunky
  • Not FSA compliant
  • Unlike promise, not explicit about the states of the action, and easy to be ignored.

Promise middleware

RXJS

  • Reactive extension for JavaScript
  • If Functional Reactive Programming is your thing, this is the library for you
  • it is a good abstraction, but it doesn't feel like it belongs in JavaScript
  • DSL is huge and confusing
  • Many really smart people love it so from your own opinion
  • However, don't use with redux

Reux-saga

  • A Redux implementation of the Saga pattern
  • Based on generators
  • Instead of dispatching Thunks, you create Sagas to gather all your Side Effects logic in a central place
  • This means application logic lives in 2 places
    • Reducers are responsible for handling state transitions between actions
    • Sagas are responsible for orchestrating complex/asynchronous operations

Saga-Pattern

Redux Saga

  • Is showing a lot of promise

Module 2: Redux Crash Course

What is Redux

  • Offically: Redux is a predictable state container for JS apps. Bascially it's a functions approach to managing state.
  • Designed with React in mind, but can be used with any rendering library
  • Excellent developer experince
  • Like React, it works on the client, server and native environments
  • Ability to rewind our state aka time traveling. Makes testing easy
  • Extremely small (around 300 lines of code)

Three parts of Redux

Part 1: The Store

  • Unlike Flux, all the state of your application lives in just one single store in Redux.
  • Single source of truth
  • This makes it easy to serialize and debug your application
  • In Practice, there is very little need for multiple stores
  • A good analogy is a simple JSON store
  • Gretting the entire state of the application is easy
  • To get the truth, just call getState

Part 2: Actions

  • State is read-only. In other words it's immutable
  • To change the state, you need to dispatch an "event" or "action" to the store.
  • Basically, actions describe what happened which the store figures out how to handle

Part 3: The Reducer

  • The store uses a reducer function to determine how to handle actions and update the state

  • A reducer is a pure function with no side effects (does not change the environment)

  • Nice to have a central place for constants (fewer spelling errors and such)

Module 3: Redux Middleware

What is middleware?

  • Middleware is computer software that procides services to software applications beyond those available from the operating system. It can be described as "software glue".
  • Ruby on Rails and Koa.js have robust middleware sysatems to deal with requests before they're handled by the main application
  • Middleware on the server is used to

Redux and the middleware patter

  • In the case of REdux middleware the main execution task is the store's dispatch function
  • The dispatch functon is responsible for sending actions to one or many reducer functions for state changes
  • Redux middleware is designed by creating function

Async in redux

  • out of the box, redux does not support async actions.

implementation details

  • Redux chains together middleware you provide, passing in special functions to your each middleware
export default store => next => action => {
	let result = next(action);
	console.log('dispatching', action);
	console.log('next state', store.getState());
	return result
}

Currying

  • a curried function can accept some of it's arguments, returning a function that takes the remaining arguments
  • this is useful if you want to apply an argument

Next

  • next() is the next middleware in the chain of middlewares. Perhaps it should have been called nextMiddleware() for clarity

  • only your middleware konws when

  • dispatch starts from the beginning; next goes to the next middleware

Module 4: Thunk and Promises

Thunk middleware

  • Redux documentation recommends redux-thunk
  • A thunk is a function that wraps an expression to delay its evaluation

Redux Thunk

  • normal actions are objects
  • redux-thunk allows you to dispatch a function which will be called by redux-thunk middleware
  • redux-thunk will pass in dispatcher and getState functions so you can dispatch an action at the end of the function.

Pros

  • very simple abstraction. you can write this yourself

Cons

  • dependency injection
  • Too easy to forget error handling and pending state

Promise middleware

  • very similar to thunk middleware but better
  • Most redux proise middleware libraries are already FSA compliatn
  • Promises are in the language and are built for async
  • Much easier to remember to catch errors and do things with it
  • https://github.com/pburtchaell/redux-promise-middleware

Module 5: Redux-Saga

Generators

  • Generators are functions which can be exited and later re-entered. Their context(variable bindings_ will be saved across re-entrances.
  • Generators have 2 parts
function* fibonacciGenerator(n) {
	let back2 = 0;
	let back1 = 1;
	let current = 0;
	for (let i = 0; i < n - 1; ++i) {
		current = back1 + back2;
		back2 = back1;
		back1 = current;
		yield current;
	}
	
	return current;
}

const fibonacci = fibonacciGenerator(10);

const interval = setInterval(() => {
	const result = fibonacci.next();
	if (result.done) {
		console.log('DONE!');
		clearInterval(interval);
		return;
	}
	console.log(result.value);
}, 0);	

Redux-Saga

  • A Redux implementation of the Saga Pattern
  • Based on generators
  • Instead of dispatching Thunks, you create Sagas to gather all your Side Effects logic in a central place.
  • This means application logic lives in 2 places:
    • Reducers are responsible for handling state transitions between actions
    • Sagas are responsible for orchestrating complex/asynchronous operations
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment