SlideShare una empresa de Scribd logo
1 de 21
Redux
yet another flux implementation ?
Nils Petersohn | twitter.com/snackycracky | alan@turing.technology
agenda
• main ideas and overview of redux components
• actions as pure functions
• immutability and mutations in redux
• sync flow
• functional composition and redux middleware
• async actions
• reactjs bindings
• experiences refactoring to redux
what does it do ?
• architecture to manage state
• Redux attempts to make state mutations predictable by putting
restrictions on how and when updates can happen.
• does not attempt to solve the problems that Relay wants to
solve
• Relies heavily on functional programming paradigms
ideas and components
• Single source of truth
• The state is stored in an object tree inside a single store.
• State is read-only
• The only way to mutate the state is to emit an action, an
object describing what happened.
• Mutations are written as pure functions
• logic for changes triggered by those actions is inside
“pure reducers”.
pure functions
• are encapsulated constructs with deterministic
behaviour
• trivial but predictable aka. easy testable
• end up with hundreds of ever repeating arguments?
• no, higher order functions and function compositions
to the rescue
redux-actions as pure
functions
• important difference to Flux: no dispatching inside
the action
• there is no Dispatcher at all; pure functions do not
need to be managed, they need to be composed.
//Action

function addGoing(memberId){

return { action: "ADD_GOING", memberId: memberId };

}
immutability
• once “something” is created, it can’t be changed anymore
• how to mutate then ?
• make a new “something” with the desired changes
• benefits ?
• 100% sure that this “something” is not changed while being
passed around in the flow.
• don't have to worry about the underlying data being changed by
another entity
• (concurrency)
reducers
• invoked with current state and the desired actions as
arguments to change the state create a new state
• one store also means one reducer ?
• no, there can be multiple reducers for the central
store. Also reducers calling other reducers is
common to modify deeply nested states.
• redux will bind them together with
`combineReducers(reducerList)` where each
of them manages it’s own part of the global state
example: List on meetup-page where people can RSVP
immutability with reducers
const initState = Immutable.Map({

title: "", organiser: "", founded: "", going: [], notGoing: []

})



//reducer

function reducingMeetupPage(state = initState, action){

if(action.type == "ADD_GOING"){

return state.update("going", (going) => going.add(action.memberId));

}

if(action.type == “ADD_NOT_GOING”){ 

let clonedNotGoing = state.toJS().notGoing;

clonedNotGoing.push(action.memberId);
//ES6 spread syntax w/o ImmutableJS:

return {...state.toJS(), notGoing: clonedNotGoing};

}

return state;

}



//Actions

function addGoing(memberId){

return { action: "ADD_GOING", memberId: memberId }; //pure: without dispatching

}



function addNotGoing(memberId){

return { action: “ADD_NOT_GOING", memberId: memberId};

}
a smart react container
• connects to everything redux.
• actions and state are injected in the props
• avoid rendering HTML, let the dumb components do that
import {addGoing, addNotGoing} from "reducers/meetup"

import {hideAlerts} from "reducers/users" 



@connect(

state => ({

going: state.visibleMeetup.going,

notGoing: state.visibleMeetup.notGoing,

comments: state.visibleMeetup.comments,

memberId: state.user.memberId,

userAlerts: state.user.alerts

}), 

dispatch => bindActionCreators({

addGoing, 

addNotGoing, 

hideAlerts}, dispatch)) 

export default class MeetupPage extends Component {

render() {

const {going,notGoing,addGoing,addNotGoing,userAlerts,hideAlerts,memberId} = this.props;

<div>

<UserInfo userNotifications={userAlerts} hideAlerts={hideAlerts}/> 

<AllOtherPageContent allOtherActions={...} />

<GoingNotGoingComponent addGoing={addGoing} going={going} ... />

</div>

}

}
a dumb react component
export default class GoingNotGoingComponent extends Component {

render() {



const {going, notGoing, memberId, addGoing, addNotGoing}= this.props;



<div>

<button onClick={addGoing.bind(null, memberId)}>I am Going</button>

<ul className="going">

{going.map(member => return <li>{member}</li>)}

</ul>



<hr/>



<button onClick={addNotGoing.bind(null, memberId)}>I am NOT Going</button>

<ul className="notGoing">

{going.map(member => <li>{user}</li>)}

</ul>

</div>

}

}
• does not know anything about redux.
• actions and state are injected in the props … again
• final payload is rendered here
sync flow
• Action -> Reducer -> SmartContainer -> DumbComponent
ui
smart Component
injected state
imported
Action Objects
wrapped with
dispatch
redux
Action
Objects / functions
ReducerReducer
Store
dumb Component
references to actions
dumb Component
references to actions
function composition
• currying = preconfigured functions being configured a little more
http://stackoverflow.com/a/218055/170881
• checkout lodashs collection of higher order functions
like _.compose, _.curry, _.partial
middleware architecture with
functional composition
• It provides a third-party extension point between dispatching an
action, and the moment it reaches the reducer.
• People use Redux middleware for logging, crash reporting, talking
to an asynchronous API, routing, and more.
const logger = store => next => action => {

console.log('dispatching', action);

let result = next(action);

console.log('next state', store.getState());

return result;

};



let createStoreWithMiddleware = applyMiddleware(logger,...)(createStore);

let myApp = combineReducers(reducers);

let store = createStoreWithMiddleware(myApp);
Async Actions• middleware can be used to check if the action contains promises and
can execute them
• In more complex apps you might want to use Rx for resolving async
actions instead, and feed an observable of actions into Redux.
export default function asyncActionsMiddleware(client) {

return ({dispatch, getState}) => {

return next => action => {

const { promise, types, ...rest } = action;


if (!promise) {

return next(action);

}



const [REQUEST, SUCCESS, FAILURE] = types;

next({...rest, type: REQUEST});

return promise(client).then(

(result) => next({...rest, result, type: SUCCESS}),

(error) => next({...rest, error, type: FAILURE})

).catch((error)=> {

console.error('MIDDLEWARE ERROR:', error);

next({...rest, error, type: FAILURE});

});

};

};

}

one Async Flow = two Sync Flows
redux
Action
Objects / functions
ReducerReducer
Store
Middleware for API-
Calls
backend
1. request
1. disposing action for
REQUESTING_DATA
2. response
2. disposing action for
DATA_RECIEVED
ui
smart Component
injected state
imported
Action Objects
wrapped with
dispatch
dumb Component
references to actions
dumb Component
references to actions
1. show spinner
2. show data
API Endpoints
react and flux inventory
• 4 Views, 20 react-components and 12 stores.
• one central view with a datagrid where data is shown
• 6 stores in 3 views contribute to the datagrid's display
properties:
• UserRolesStore, datagrid(-DataStore, -FilterStore, -
ContextStore, -SortingStore, -AggregationStore)
• components influence the store but also retrieved data
influences the store and therefore the components as
well.
benefits of refactoring to redux
• a single store made sense because all Components contributing to
one major backend call (getData and show in table)
• the stores state is now observed by Rx.Observable for changes and
a new backend call
• Better architecture with more dumb components which have the
properties injected instead of getting them from the store themselves.
• system feels more encapsulated with high cohesion (reducers and
one store) and looser coupling (killing the store calls in the
components)
• functional programming paradigms are enforced by design => easier
unit tests
boilerplate
• using https://github.com/erikras/react-redux-
universal-hot-example
• hooked in the boilerplate code as light as possible,
to pull changes from the original repository very
frequently.
• matter to drastically update in the future. Hourly
Changes are happening there.
references
http://rackt.org/redux/docs
Functional JavaScript
Michael Fogus O’Reilly 2013
Reactive Programming with JavaScript
Jonathan Hayward Packt 2015
https://github.com/xgrommx/awesome-redux

Más contenido relacionado

La actualidad más candente

La actualidad más candente (20)

How to Redux
How to ReduxHow to Redux
How to Redux
 
React.js+Redux Workshops
React.js+Redux WorkshopsReact.js+Redux Workshops
React.js+Redux Workshops
 
Redux Universal
Redux UniversalRedux Universal
Redux Universal
 
Angular redux
Angular reduxAngular redux
Angular redux
 
React + Redux + TypeScript === ♥
React + Redux + TypeScript === ♥React + Redux + TypeScript === ♥
React + Redux + TypeScript === ♥
 
React for Dummies
React for DummiesReact for Dummies
React for Dummies
 
Let's Redux!
Let's Redux!Let's Redux!
Let's Redux!
 
React.js and Redux overview
React.js and Redux overviewReact.js and Redux overview
React.js and Redux overview
 
React js
React jsReact js
React js
 
React / Redux Architectures
React / Redux ArchitecturesReact / Redux Architectures
React / Redux Architectures
 
Better web apps with React and Redux
Better web apps with React and ReduxBetter web apps with React and Redux
Better web apps with React and Redux
 
Academy PRO: React JS. Redux & Tooling
Academy PRO: React JS. Redux & ToolingAcademy PRO: React JS. Redux & Tooling
Academy PRO: React JS. Redux & Tooling
 
React state managmenet with Redux
React state managmenet with ReduxReact state managmenet with Redux
React state managmenet with Redux
 
React, Flux and a little bit of Redux
React, Flux and a little bit of ReduxReact, Flux and a little bit of Redux
React, Flux and a little bit of Redux
 
A Brief Introduction to React.js
A Brief Introduction to React.jsA Brief Introduction to React.js
A Brief Introduction to React.js
 
React and redux
React and reduxReact and redux
React and redux
 
Building Modern Web Applications using React and Redux
 Building Modern Web Applications using React and Redux Building Modern Web Applications using React and Redux
Building Modern Web Applications using React and Redux
 
The Road To Redux
The Road To ReduxThe Road To Redux
The Road To Redux
 
React & redux
React & reduxReact & redux
React & redux
 
Introduction to React & Redux
Introduction to React & ReduxIntroduction to React & Redux
Introduction to React & Redux
 

Destacado (9)

React + Redux Introduction
React + Redux IntroductionReact + Redux Introduction
React + Redux Introduction
 
Redux and redux saga
Redux and redux sagaRedux and redux saga
Redux and redux saga
 
The redux saga begins
The redux saga beginsThe redux saga begins
The redux saga begins
 
Getting Started with React-Nathan Smith
Getting Started with React-Nathan SmithGetting Started with React-Nathan Smith
Getting Started with React-Nathan Smith
 
React & Redux
React & ReduxReact & Redux
React & Redux
 
An Introduction to ReactJS
An Introduction to ReactJSAn Introduction to ReactJS
An Introduction to ReactJS
 
Linux Kernel Tour
Linux Kernel TourLinux Kernel Tour
Linux Kernel Tour
 
React JS and why it's awesome
React JS and why it's awesomeReact JS and why it's awesome
React JS and why it's awesome
 
How to deploy PHP projects with docker
How to deploy PHP projects with dockerHow to deploy PHP projects with docker
How to deploy PHP projects with docker
 

Similar a Redux js

[Final] ReactJS presentation
[Final] ReactJS presentation[Final] ReactJS presentation
[Final] ReactJS presentation
洪 鹏发
 
Evan Schultz - Angular Summit - 2016
Evan Schultz - Angular Summit - 2016Evan Schultz - Angular Summit - 2016
Evan Schultz - Angular Summit - 2016
Evan Schultz
 

Similar a Redux js (20)

Redux data flow with angular 2
Redux data flow with angular 2Redux data flow with angular 2
Redux data flow with angular 2
 
Redux data flow with angular
Redux data flow with angularRedux data flow with angular
Redux data flow with angular
 
Redux data flow with angular
Redux data flow with angularRedux data flow with angular
Redux data flow with angular
 
[Final] ReactJS presentation
[Final] ReactJS presentation[Final] ReactJS presentation
[Final] ReactJS presentation
 
Evan Schultz - Angular Summit - 2016
Evan Schultz - Angular Summit - 2016Evan Schultz - Angular Summit - 2016
Evan Schultz - Angular Summit - 2016
 
Reactive state management with Jetpack Components
Reactive state management with Jetpack ComponentsReactive state management with Jetpack Components
Reactive state management with Jetpack Components
 
Road to react hooks
Road to react hooksRoad to react hooks
Road to react hooks
 
ReactJS presentation.pptx
ReactJS presentation.pptxReactJS presentation.pptx
ReactJS presentation.pptx
 
Redux Tech Talk
Redux Tech TalkRedux Tech Talk
Redux Tech Talk
 
ReactJS
ReactJSReactJS
ReactJS
 
Reactивная тяга
Reactивная тягаReactивная тяга
Reactивная тяга
 
Spfx with react redux
Spfx with react reduxSpfx with react redux
Spfx with react redux
 
Workshop 22: ReactJS Redux Advanced
Workshop 22: ReactJS Redux AdvancedWorkshop 22: ReactJS Redux Advanced
Workshop 22: ReactJS Redux Advanced
 
Workshop 22: React-Redux Middleware
Workshop 22: React-Redux MiddlewareWorkshop 22: React-Redux Middleware
Workshop 22: React-Redux Middleware
 
Making react part of something greater
Making react part of something greaterMaking react part of something greater
Making react part of something greater
 
What 100M downloads taught us about iOS architectures
What 100M downloads taught us about iOS architecturesWhat 100M downloads taught us about iOS architectures
What 100M downloads taught us about iOS architectures
 
React js
React jsReact js
React js
 
Using React, Redux and Saga with Lottoland APIs
Using React, Redux and Saga with Lottoland APIsUsing React, Redux and Saga with Lottoland APIs
Using React, Redux and Saga with Lottoland APIs
 
Adding a modern twist to legacy web applications
Adding a modern twist to legacy web applicationsAdding a modern twist to legacy web applications
Adding a modern twist to legacy web applications
 
React
ReactReact
React
 

Último

Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
panagenda
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 

Último (20)

Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptx
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
 
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
 
Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
Ransomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfRansomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdf
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
A Beginners Guide to Building a RAG App Using Open Source Milvus
A Beginners Guide to Building a RAG App Using Open Source MilvusA Beginners Guide to Building a RAG App Using Open Source Milvus
A Beginners Guide to Building a RAG App Using Open Source Milvus
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 

Redux js

  • 1. Redux yet another flux implementation ? Nils Petersohn | twitter.com/snackycracky | alan@turing.technology
  • 2. agenda • main ideas and overview of redux components • actions as pure functions • immutability and mutations in redux • sync flow • functional composition and redux middleware • async actions • reactjs bindings • experiences refactoring to redux
  • 3. what does it do ? • architecture to manage state • Redux attempts to make state mutations predictable by putting restrictions on how and when updates can happen. • does not attempt to solve the problems that Relay wants to solve • Relies heavily on functional programming paradigms
  • 4. ideas and components • Single source of truth • The state is stored in an object tree inside a single store. • State is read-only • The only way to mutate the state is to emit an action, an object describing what happened. • Mutations are written as pure functions • logic for changes triggered by those actions is inside “pure reducers”.
  • 5. pure functions • are encapsulated constructs with deterministic behaviour • trivial but predictable aka. easy testable • end up with hundreds of ever repeating arguments? • no, higher order functions and function compositions to the rescue
  • 6. redux-actions as pure functions • important difference to Flux: no dispatching inside the action • there is no Dispatcher at all; pure functions do not need to be managed, they need to be composed. //Action
 function addGoing(memberId){
 return { action: "ADD_GOING", memberId: memberId };
 }
  • 7. immutability • once “something” is created, it can’t be changed anymore • how to mutate then ? • make a new “something” with the desired changes • benefits ? • 100% sure that this “something” is not changed while being passed around in the flow. • don't have to worry about the underlying data being changed by another entity • (concurrency)
  • 8. reducers • invoked with current state and the desired actions as arguments to change the state create a new state • one store also means one reducer ? • no, there can be multiple reducers for the central store. Also reducers calling other reducers is common to modify deeply nested states. • redux will bind them together with `combineReducers(reducerList)` where each of them manages it’s own part of the global state
  • 9. example: List on meetup-page where people can RSVP
  • 10. immutability with reducers const initState = Immutable.Map({
 title: "", organiser: "", founded: "", going: [], notGoing: []
 })
 
 //reducer
 function reducingMeetupPage(state = initState, action){
 if(action.type == "ADD_GOING"){
 return state.update("going", (going) => going.add(action.memberId));
 }
 if(action.type == “ADD_NOT_GOING”){ 
 let clonedNotGoing = state.toJS().notGoing;
 clonedNotGoing.push(action.memberId); //ES6 spread syntax w/o ImmutableJS:
 return {...state.toJS(), notGoing: clonedNotGoing};
 }
 return state;
 }
 
 //Actions
 function addGoing(memberId){
 return { action: "ADD_GOING", memberId: memberId }; //pure: without dispatching
 }
 
 function addNotGoing(memberId){
 return { action: “ADD_NOT_GOING", memberId: memberId};
 }
  • 11. a smart react container • connects to everything redux. • actions and state are injected in the props • avoid rendering HTML, let the dumb components do that import {addGoing, addNotGoing} from "reducers/meetup"
 import {hideAlerts} from "reducers/users" 
 
 @connect(
 state => ({
 going: state.visibleMeetup.going,
 notGoing: state.visibleMeetup.notGoing,
 comments: state.visibleMeetup.comments,
 memberId: state.user.memberId,
 userAlerts: state.user.alerts
 }), 
 dispatch => bindActionCreators({
 addGoing, 
 addNotGoing, 
 hideAlerts}, dispatch)) 
 export default class MeetupPage extends Component {
 render() {
 const {going,notGoing,addGoing,addNotGoing,userAlerts,hideAlerts,memberId} = this.props;
 <div>
 <UserInfo userNotifications={userAlerts} hideAlerts={hideAlerts}/> 
 <AllOtherPageContent allOtherActions={...} />
 <GoingNotGoingComponent addGoing={addGoing} going={going} ... />
 </div>
 }
 }
  • 12. a dumb react component export default class GoingNotGoingComponent extends Component {
 render() {
 
 const {going, notGoing, memberId, addGoing, addNotGoing}= this.props;
 
 <div>
 <button onClick={addGoing.bind(null, memberId)}>I am Going</button>
 <ul className="going">
 {going.map(member => return <li>{member}</li>)}
 </ul>
 
 <hr/>
 
 <button onClick={addNotGoing.bind(null, memberId)}>I am NOT Going</button>
 <ul className="notGoing">
 {going.map(member => <li>{user}</li>)}
 </ul>
 </div>
 }
 } • does not know anything about redux. • actions and state are injected in the props … again • final payload is rendered here
  • 13. sync flow • Action -> Reducer -> SmartContainer -> DumbComponent ui smart Component injected state imported Action Objects wrapped with dispatch redux Action Objects / functions ReducerReducer Store dumb Component references to actions dumb Component references to actions
  • 14. function composition • currying = preconfigured functions being configured a little more http://stackoverflow.com/a/218055/170881 • checkout lodashs collection of higher order functions like _.compose, _.curry, _.partial
  • 15. middleware architecture with functional composition • It provides a third-party extension point between dispatching an action, and the moment it reaches the reducer. • People use Redux middleware for logging, crash reporting, talking to an asynchronous API, routing, and more. const logger = store => next => action => {
 console.log('dispatching', action);
 let result = next(action);
 console.log('next state', store.getState());
 return result;
 };
 
 let createStoreWithMiddleware = applyMiddleware(logger,...)(createStore);
 let myApp = combineReducers(reducers);
 let store = createStoreWithMiddleware(myApp);
  • 16. Async Actions• middleware can be used to check if the action contains promises and can execute them • In more complex apps you might want to use Rx for resolving async actions instead, and feed an observable of actions into Redux. export default function asyncActionsMiddleware(client) {
 return ({dispatch, getState}) => {
 return next => action => {
 const { promise, types, ...rest } = action; 
 if (!promise) {
 return next(action);
 }
 
 const [REQUEST, SUCCESS, FAILURE] = types;
 next({...rest, type: REQUEST});
 return promise(client).then(
 (result) => next({...rest, result, type: SUCCESS}),
 (error) => next({...rest, error, type: FAILURE})
 ).catch((error)=> {
 console.error('MIDDLEWARE ERROR:', error);
 next({...rest, error, type: FAILURE});
 });
 };
 };
 }

  • 17. one Async Flow = two Sync Flows redux Action Objects / functions ReducerReducer Store Middleware for API- Calls backend 1. request 1. disposing action for REQUESTING_DATA 2. response 2. disposing action for DATA_RECIEVED ui smart Component injected state imported Action Objects wrapped with dispatch dumb Component references to actions dumb Component references to actions 1. show spinner 2. show data API Endpoints
  • 18. react and flux inventory • 4 Views, 20 react-components and 12 stores. • one central view with a datagrid where data is shown • 6 stores in 3 views contribute to the datagrid's display properties: • UserRolesStore, datagrid(-DataStore, -FilterStore, - ContextStore, -SortingStore, -AggregationStore) • components influence the store but also retrieved data influences the store and therefore the components as well.
  • 19. benefits of refactoring to redux • a single store made sense because all Components contributing to one major backend call (getData and show in table) • the stores state is now observed by Rx.Observable for changes and a new backend call • Better architecture with more dumb components which have the properties injected instead of getting them from the store themselves. • system feels more encapsulated with high cohesion (reducers and one store) and looser coupling (killing the store calls in the components) • functional programming paradigms are enforced by design => easier unit tests
  • 20. boilerplate • using https://github.com/erikras/react-redux- universal-hot-example • hooked in the boilerplate code as light as possible, to pull changes from the original repository very frequently. • matter to drastically update in the future. Hourly Changes are happening there.
  • 21. references http://rackt.org/redux/docs Functional JavaScript Michael Fogus O’Reilly 2013 Reactive Programming with JavaScript Jonathan Hayward Packt 2015 https://github.com/xgrommx/awesome-redux