SlideShare a Scribd company logo
Building React Applications with Redux
Image by mulad
Many people choose to
think of React as the V in
MVC.
– β€œWhy React?” in React documentation
β€œ
MVC in Theory
Image by mulad
Model( Ν‘Β° ΝœΚ– Ν‘Β°)
View
Controller
MVC in Practice
Image by mulad
View Model Model
Model
Model
Model
View Model
View Model
View Model ΰ² _ΰ² 
Isolated (β€œDumb”) Components
Parent
Child
Props Callbacks
Maximize your use of β€œdumb” components.
Advantages of Isolated Components
β€’ Helps with code reuse.
β€’ Helps with testing.
β€’ Makes it easy to reason about your code.
Image by mulad
Sources of Those Benefits
β€’ Dumb components are isolation from the rest of the
application.
β€’ Dumb components are mostly stateless.
Image by mulad
Trouble with State
β€’ A lot of us were raised on OOP. Objects are stateful.
β€’ The effect of calling a method depends on the arguments and
the object’s state.
β€’ Very painful to test.
β€’ Very hard to understand.
β€’ Aims to mimic the real world.
β€’ But why replicate the unnecessary complexity?
Image by mulad
Alternative: Pure Functions
β€’ The output of a pure function depends only on inputs.
β€’ Pure function has no side-effects.
β€’ Much easier to understand.
β€’ Much easier to test.
β€’ Very easy to build through composition.
Image by mulad
Truly Stateless Components
Image by mulad
function HelloMessage(props) {
return <div>Hello {props.name}</div>;
}
Even Better
Image by mulad
const HelloMessage = (props) => <div>Hello {props.name}</div>;
Use stateless components whenever you can.
Where Does Business Logic Go?
β€’ Each component gets props from its parent.
β€’ Each component transmits actions to the parent.
β€’ Turtles all the way down up?
β€’ Top-level components need to be a bit smarter!
β€’ We’ll call them β€œcontainer components”.
Image by mulad
Linking Containers with Models
Image by mulad
Container Model
ModelContainer
Nevermind…
Should We Use the Container’s State?
β€’ We could, but so much for separation of concerns…
Image by mulad
What If We Did It the React Way?
???
Container Component
Props Callbacks
What If We Did It the React Way?
State Container
Container Component
Props Callbacks
Flux Architecture
State Container
Container Component
Change events Actions
Handling Data in the State Container
Component
StoreComponent
Dispatcher
Action
Handling Data in the State Container
Component
Store
API, etc.
Component
Dispatcher
Action(s)Action

Creator
We’ll see another

way of doing this.
Redux
A Better State Container
β€’ https://github.com/rackt/redux
β€’ Pretty much the dominant way of doing Flux with React
today.
β€’ Key concepts: a single store + state β€œreducers”.
β€’ Can a single store be a good idea?
β€’ What the heck is a β€œreducer”?
Reducer Functions
β€’ Basic reduce():
function addOneValue (value, state) {
return state + value;
}
[1,2,3,4,5].reduce(addOneValue, 0);
β€’ Running through the items:
1: 0 => 1
2: 1 => 3
3: 3 => 6
4: 6 => 10
5: 10 => 15
Action Reducers in Redux
β€’ Take an action and a state, return a new state.
β€’ Your app’s state is a reduction over the actions.
β€’ Each reducer operates on a subset of the global state.
β€’ Simple reducers are combined into complex ones.
Creating an Action
const UPDATE_NOTE_CONTENT = 'App/UPDATE_NOTE_CONTENT';
function updateNoteContent(noteId, newContent) {
return {
type: UPDATE_NOTE_CONTENT,
payload: {
noteId: noteId,
newContent: newContent
}
}
}
Creating an Action, more ES6
const UPDATE_NOTE_CONTENT = 'App/UPDATE_NOTE_CONTENT';
const updateNoteContent = (noteId, newContent) => ({
type: UPDATE_NOTE_CONTENT,
payload: {noteId, newContent}
});
A Reducer
export const notes = createReducer({
[UPDATE_NOTE_CONTENT]: (state, action) => state.setIn(
['byId', action.payload.noteId, 'html'],
action.payload.newContent
),
[SOME_OTHER_ACTION]: (state, action) => {
// do something else or just
return state;
}),
});
A Reducer, more ES5ish
export const notes = createReducer({
[UPDATE_NOTE_CONTENT]: function (state, action) {
return state.setIn(
['byId', action.payload.noteId, 'html'],
action.payload.newContent
);
},
[SOME_OTHER_ACTION]: function (state, action) {
// do something else or just
return state;
},
});
Why Is This a Good Idea?
β€’ Reducers are pure functions – easy to understand, easy to
test.
β€’ Reducers are synchronous.
β€’ Data logic is 100% separated from view logic.
β€’ You can still have modularity by combining reducers.
β€’ New opportunities for tools.
How Do We Avoid Mutating State?
β€’ Reducers are supposed to not change the old state. But how
do we keep them honest?
β€’ One option is to clone the object every time.
β€’ β€œImmutable.JS” is the library to use.
var newData = data.setIn(
['foo', 'bar', 'baz'],
42
);
β€’ This is a key building block for stateless architecture.
The Reducer Example Again
export const notes = createReducer({
[UPDATE_NOTE_CONTENT]: (state, action) => state.setIn(
['byId', action.payload.noteId, 'html'],
action.payload.newContent
),
[SOME_OTHER_ACTION]: (state, action) => {
// do something else or just
return state;
}),
});
Connecting Container Components
import { connect } from 'react-redux';
export default connect(
mapStateToProps,
mapDispatchToProps,
)(MainPage);
React-Redux Mapping Functions
function mapStateToProps(state) {
const notesAsJS = state.notes.toJS();
return {
notes: notesAsJS.ordered.map((id) => notesAsJS.byId[id])
};
}
function mapDispatchToProps(dispatch) {
return {
onContentChange: (noteId, newContent) =>
dispatch(noteActions.updateNoteContent(
noteId, newContent)),
};
}
Handling Asyncronous Actions
β€’ Option 1: β€œSmart” actions creators.
β€’ Option 2: Middleware.
β€’ Option 2β€²: React Sagas.
Smart Action Creators
β€’ Call an action creator to initiate a request.
β€’ The action creator emits an action to inform everyone that a
request was made.
β€’ The action creator makes a request.
β€’ If the request succeeds, the action creator emits an action to
inform everyone that a request was completed. (Same for
failure and timeout.)
β€’ The details of interacting with the server should be pushed
into a module.
An Example, Part 1
function makeFetchNotesAction(status, data) {
return {
type: FETCH_NOTES,
payload: {
status: status,
data: data
}
};
}
An Example, Part 1
export function fetchNotes() {
return dispatch => {
dispatch(makeFetchNotesAction('request'));
return fetchData()
.then(json => dispatch(makeFetchNotesAction('success', json)))
.catch(error => dispatch(makeFetchNotesAction('error', error)));
};
}
Alternatively: Redux Middleware
β€’ A middleware is a function that allows you to capture actions
and do something before they get to the reducers.
β€’ This can include things like API calls.
β€’ More generally, the sky is the limit.
β€’ Perhaps a little too generic for many cases.
Alternative: Redux Sagas
β€’ A middleware that works with generators.
β€’ Awesome, if you understand generators.
β€’ Can simplify complex workflows.
β€’ Very new.
Redux Sagas Example
function* fetchNotesForStack(action) {
const stackId = action.payload.stackId;
yield put(getNotes.request());
const {data, error} = yield dataApi.getNotesForStack(stackId);
if (!error) {
yield put(getNotes.success(organizeNotes(data.notes)));
} else {
yield put(getNotes.failure(error));
}
}
function* watchFetchNotesForStack() {
yield* takeEvery(SELECT_STACK, fetchNotesForStack);
}
Testing Is Easy
describe('on ADD_NOTE', () => {
it('should create a new note', () => {
const getNoteCount = () => initialState.toJS().ordered.length;
const previousCount = getNoteCount();
const newState = notesReducer(initialState, {type: ADD_NOTE});
assert.strictEqual(previousCount + 1, getNoteCount());
const newNoteId = newState.toJS().ordered[0];
const newNoteHtml = newState.getIn(['byId', newNoteId, 'html']);
assert.strictEqual(newNoteHtml, 'No content');
});
});
Caveats
β€’ Its addictive.
β€’ You won’t be happy using anything else.
β€’ Your friends might not understand your obsession.
THANK YOU!
Yuri Takhteyev
@qaramazov
rangle
CTO, Rangle.io
Some rights reserved - Creative Commons 2.0 by-sa

More Related Content

PDF
Let's Redux!
PDF
State Models for React with Redux
PPTX
ProvJS: Six Months of ReactJS and Redux
PPTX
Better React state management with Redux
PDF
The Road To Redux
PDF
Let's discover React and Redux with TypeScript
PDF
Redux js
PDF
React & Redux
Let's Redux!
State Models for React with Redux
ProvJS: Six Months of ReactJS and Redux
Better React state management with Redux
The Road To Redux
Let's discover React and Redux with TypeScript
Redux js
React & Redux

What's hot (20)

PDF
Designing applications with Redux
PPTX
React + Redux + TypeScript === β™₯
PDF
React for Dummies
PDF
An Introduction to ReactJS
PDF
Introduction to Redux
PPTX
Getting started with Redux js
Β 
PDF
React.js and Redux overview
PPTX
React, Flux and a little bit of Redux
PDF
Angular redux
PPT
React js
PDF
React redux
PDF
React state managmenet with Redux
PDF
React + Redux. Best practices
PPTX
Academy PRO: React JS. Redux & Tooling
PPTX
React / Redux Architectures
PDF
Using redux
PPTX
React + Redux Introduction
PPTX
Redux training
PDF
Introduction to React & Redux
PPTX
Introduction to react and redux
Designing applications with Redux
React + Redux + TypeScript === β™₯
React for Dummies
An Introduction to ReactJS
Introduction to Redux
Getting started with Redux js
Β 
React.js and Redux overview
React, Flux and a little bit of Redux
Angular redux
React js
React redux
React state managmenet with Redux
React + Redux. Best practices
Academy PRO: React JS. Redux & Tooling
React / Redux Architectures
Using redux
React + Redux Introduction
Redux training
Introduction to React & Redux
Introduction to react and redux
Ad

Viewers also liked (20)

PDF
React JS and why it's awesome
PDF
React.js in real world apps.
PDF
How to Redux
PDF
Robust web apps with React.js
PPTX
Flux and redux
PPTX
Reducers+flux=redux
PDF
React&redux
PDF
Redux vs Alt
PPTX
Angular js com diretivas
PPTX
ApresentaΓ§Γ£o AngularJS - Angular UI
PDF
An Intense Overview of the React Ecosystem
PPTX
React, Flux y React native
PDF
React – ΒΏQuΓ© es React.js?
PDF
JSConf US 2014: Building Isomorphic Apps
PDF
Migrating from Flux to Redux. Why and how.
PPTX
React. Flux. Redux
PDF
Soa Fundamentos
PDF
Arquitetura Orientada a Servicos (SOA)
PDF
Angular js
PPTX
Criando serviΓ§os com AngularJS
React JS and why it's awesome
React.js in real world apps.
How to Redux
Robust web apps with React.js
Flux and redux
Reducers+flux=redux
React&redux
Redux vs Alt
Angular js com diretivas
ApresentaΓ§Γ£o AngularJS - Angular UI
An Intense Overview of the React Ecosystem
React, Flux y React native
React – ΒΏQuΓ© es React.js?
JSConf US 2014: Building Isomorphic Apps
Migrating from Flux to Redux. Why and how.
React. Flux. Redux
Soa Fundamentos
Arquitetura Orientada a Servicos (SOA)
Angular js
Criando serviΓ§os com AngularJS
Ad

Similar to Building React Applications with Redux (20)

PDF
Redux essentials
PPTX
Maintaining sanity in a large redux app
PPTX
Redux
PDF
Understanding redux
PPTX
React.js at Cortex
PDF
Getting started with React and Redux
PDF
[@NaukriEngineering] Flux Architecture
PDF
Evan Schultz - Angular Summit - 2016
PPTX
Redux workshop
PPTX
React & redux
PPTX
React + Flux = Joy
PPTX
React/Redux
PDF
ReactRedux.pdf
PDF
React Interview Question & Answers PDF By ScholarHat
PPTX
an Introduction to Redux
PDF
A React Journey
PDF
React and redux
PPTX
unit 2 Mastering-State-Management-in-React.pptx
PDF
Manage the Flux of your Web Application: Let's Redux
PDF
Content-Driven Apps with React
Redux essentials
Maintaining sanity in a large redux app
Redux
Understanding redux
React.js at Cortex
Getting started with React and Redux
[@NaukriEngineering] Flux Architecture
Evan Schultz - Angular Summit - 2016
Redux workshop
React & redux
React + Flux = Joy
React/Redux
ReactRedux.pdf
React Interview Question & Answers PDF By ScholarHat
an Introduction to Redux
A React Journey
React and redux
unit 2 Mastering-State-Management-in-React.pptx
Manage the Flux of your Web Application: Let's Redux
Content-Driven Apps with React

More from FITC (20)

PPTX
Cut it up
Β 
PDF
Designing for Digital Health
Β 
PDF
Profiling JavaScript Performance
Β 
PPTX
Surviving Your Tech Stack
Β 
PDF
How to Pitch Your First AR Project
Β 
PDF
Start by Understanding the Problem, Not by Delivering the Answer
Β 
PDF
Cocaine to Carrots: The Art of Telling Someone Else’s Story
Β 
PDF
Everyday Innovation
Β 
PDF
HyperLight Websites
Β 
PDF
Everything is Terrifying
Β 
PDF
Post-Earth Visions: Designing for Space and the Future Human
Β 
PDF
The Rise of the Creative Social Influencer (and How to Become One)
Β 
PDF
East of the Rockies: Developing an AR Game
Β 
PDF
Creating a Proactive Healthcare System
Β 
PDF
World Transformation: The Secret Agenda of Product Design
Β 
PDF
The Power of Now
Β 
PDF
High Performance PWAs
Β 
PDF
Rise of the JAMstack
Β 
PDF
From Closed to Open: A Journey of Self Discovery
Β 
PDF
Projects Ain’t Nobody Got Time For
Β 
Cut it up
Β 
Designing for Digital Health
Β 
Profiling JavaScript Performance
Β 
Surviving Your Tech Stack
Β 
How to Pitch Your First AR Project
Β 
Start by Understanding the Problem, Not by Delivering the Answer
Β 
Cocaine to Carrots: The Art of Telling Someone Else’s Story
Β 
Everyday Innovation
Β 
HyperLight Websites
Β 
Everything is Terrifying
Β 
Post-Earth Visions: Designing for Space and the Future Human
Β 
The Rise of the Creative Social Influencer (and How to Become One)
Β 
East of the Rockies: Developing an AR Game
Β 
Creating a Proactive Healthcare System
Β 
World Transformation: The Secret Agenda of Product Design
Β 
The Power of Now
Β 
High Performance PWAs
Β 
Rise of the JAMstack
Β 
From Closed to Open: A Journey of Self Discovery
Β 
Projects Ain’t Nobody Got Time For
Β 

Recently uploaded (20)

PPTX
Slides PPTX World Game (s) Eco Economic Epochs.pptx
PPTX
Digital Literacy And Online Safety on internet
PDF
Testing WebRTC applications at scale.pdf
PDF
πŸ’° π”πŠπ“πˆ πŠπ„πŒπ„ππ€ππ†π€π πŠπˆππ„π‘πŸ’πƒ π‡π€π‘πˆ 𝐈𝐍𝐈 πŸπŸŽπŸπŸ“ πŸ’°
Β 
PDF
The Internet -By the Numbers, Sri Lanka Edition
Β 
PDF
Best Practices for Testing and Debugging Shopify Third-Party API Integrations...
PPTX
522797556-Unit-2-Temperature-measurement-1-1.pptx
PDF
An introduction to the IFRS (ISSB) Stndards.pdf
PPTX
presentation_pfe-universite-molay-seltan.pptx
PDF
Unit-1 introduction to cyber security discuss about how to secure a system
PDF
WebRTC in SignalWire - troubleshooting media negotiation
PPTX
Module 1 - Cyber Law and Ethics 101.pptx
PPTX
Introuction about WHO-FIC in ICD-10.pptx
PPTX
Introduction about ICD -10 and ICD11 on 5.8.25.pptx
PPTX
introduction about ICD -10 & ICD-11 ppt.pptx
PPTX
QR Codes Qr codecodecodecodecocodedecodecode
PDF
APNIC Update, presented at PHNOG 2025 by Shane Hermoso
Β 
PPTX
June-4-Sermon-Powerpoint.pptx USE THIS FOR YOUR MOTIVATION
DOCX
Unit-3 cyber security network security of internet system
PPT
Design_with_Watersergyerge45hrbgre4top (1).ppt
Slides PPTX World Game (s) Eco Economic Epochs.pptx
Digital Literacy And Online Safety on internet
Testing WebRTC applications at scale.pdf
πŸ’° π”πŠπ“πˆ πŠπ„πŒπ„ππ€ππ†π€π πŠπˆππ„π‘πŸ’πƒ π‡π€π‘πˆ 𝐈𝐍𝐈 πŸπŸŽπŸπŸ“ πŸ’°
Β 
The Internet -By the Numbers, Sri Lanka Edition
Β 
Best Practices for Testing and Debugging Shopify Third-Party API Integrations...
522797556-Unit-2-Temperature-measurement-1-1.pptx
An introduction to the IFRS (ISSB) Stndards.pdf
presentation_pfe-universite-molay-seltan.pptx
Unit-1 introduction to cyber security discuss about how to secure a system
WebRTC in SignalWire - troubleshooting media negotiation
Module 1 - Cyber Law and Ethics 101.pptx
Introuction about WHO-FIC in ICD-10.pptx
Introduction about ICD -10 and ICD11 on 5.8.25.pptx
introduction about ICD -10 & ICD-11 ppt.pptx
QR Codes Qr codecodecodecodecocodedecodecode
APNIC Update, presented at PHNOG 2025 by Shane Hermoso
Β 
June-4-Sermon-Powerpoint.pptx USE THIS FOR YOUR MOTIVATION
Unit-3 cyber security network security of internet system
Design_with_Watersergyerge45hrbgre4top (1).ppt

Building React Applications with Redux

  • 2. Image by mulad Many people choose to think of React as the V in MVC. – β€œWhy React?” in React documentation β€œ
  • 3. MVC in Theory Image by mulad Model( Ν‘Β° ΝœΚ– Ν‘Β°) View Controller
  • 4. MVC in Practice Image by mulad View Model Model Model Model Model View Model View Model View Model ΰ² _ΰ² 
  • 5. Isolated (β€œDumb”) Components Parent Child Props Callbacks Maximize your use of β€œdumb” components.
  • 6. Advantages of Isolated Components β€’ Helps with code reuse. β€’ Helps with testing. β€’ Makes it easy to reason about your code. Image by mulad
  • 7. Sources of Those Benefits β€’ Dumb components are isolation from the rest of the application. β€’ Dumb components are mostly stateless. Image by mulad
  • 8. Trouble with State β€’ A lot of us were raised on OOP. Objects are stateful. β€’ The effect of calling a method depends on the arguments and the object’s state. β€’ Very painful to test. β€’ Very hard to understand. β€’ Aims to mimic the real world. β€’ But why replicate the unnecessary complexity? Image by mulad
  • 9. Alternative: Pure Functions β€’ The output of a pure function depends only on inputs. β€’ Pure function has no side-effects. β€’ Much easier to understand. β€’ Much easier to test. β€’ Very easy to build through composition. Image by mulad
  • 10. Truly Stateless Components Image by mulad function HelloMessage(props) { return <div>Hello {props.name}</div>; }
  • 11. Even Better Image by mulad const HelloMessage = (props) => <div>Hello {props.name}</div>; Use stateless components whenever you can.
  • 12. Where Does Business Logic Go? β€’ Each component gets props from its parent. β€’ Each component transmits actions to the parent. β€’ Turtles all the way down up? β€’ Top-level components need to be a bit smarter! β€’ We’ll call them β€œcontainer components”. Image by mulad
  • 13. Linking Containers with Models Image by mulad Container Model ModelContainer Nevermind…
  • 14. Should We Use the Container’s State? β€’ We could, but so much for separation of concerns… Image by mulad
  • 15. What If We Did It the React Way? ??? Container Component Props Callbacks
  • 16. What If We Did It the React Way? State Container Container Component Props Callbacks
  • 17. Flux Architecture State Container Container Component Change events Actions
  • 18. Handling Data in the State Container Component StoreComponent Dispatcher Action
  • 19. Handling Data in the State Container Component Store API, etc. Component Dispatcher Action(s)Action
 Creator We’ll see another
 way of doing this.
  • 20. Redux
  • 21. A Better State Container β€’ https://github.com/rackt/redux β€’ Pretty much the dominant way of doing Flux with React today. β€’ Key concepts: a single store + state β€œreducers”. β€’ Can a single store be a good idea? β€’ What the heck is a β€œreducer”?
  • 22. Reducer Functions β€’ Basic reduce(): function addOneValue (value, state) { return state + value; } [1,2,3,4,5].reduce(addOneValue, 0); β€’ Running through the items: 1: 0 => 1 2: 1 => 3 3: 3 => 6 4: 6 => 10 5: 10 => 15
  • 23. Action Reducers in Redux β€’ Take an action and a state, return a new state. β€’ Your app’s state is a reduction over the actions. β€’ Each reducer operates on a subset of the global state. β€’ Simple reducers are combined into complex ones.
  • 24. Creating an Action const UPDATE_NOTE_CONTENT = 'App/UPDATE_NOTE_CONTENT'; function updateNoteContent(noteId, newContent) { return { type: UPDATE_NOTE_CONTENT, payload: { noteId: noteId, newContent: newContent } } }
  • 25. Creating an Action, more ES6 const UPDATE_NOTE_CONTENT = 'App/UPDATE_NOTE_CONTENT'; const updateNoteContent = (noteId, newContent) => ({ type: UPDATE_NOTE_CONTENT, payload: {noteId, newContent} });
  • 26. A Reducer export const notes = createReducer({ [UPDATE_NOTE_CONTENT]: (state, action) => state.setIn( ['byId', action.payload.noteId, 'html'], action.payload.newContent ), [SOME_OTHER_ACTION]: (state, action) => { // do something else or just return state; }), });
  • 27. A Reducer, more ES5ish export const notes = createReducer({ [UPDATE_NOTE_CONTENT]: function (state, action) { return state.setIn( ['byId', action.payload.noteId, 'html'], action.payload.newContent ); }, [SOME_OTHER_ACTION]: function (state, action) { // do something else or just return state; }, });
  • 28. Why Is This a Good Idea? β€’ Reducers are pure functions – easy to understand, easy to test. β€’ Reducers are synchronous. β€’ Data logic is 100% separated from view logic. β€’ You can still have modularity by combining reducers. β€’ New opportunities for tools.
  • 29. How Do We Avoid Mutating State? β€’ Reducers are supposed to not change the old state. But how do we keep them honest? β€’ One option is to clone the object every time. β€’ β€œImmutable.JS” is the library to use. var newData = data.setIn( ['foo', 'bar', 'baz'], 42 ); β€’ This is a key building block for stateless architecture.
  • 30. The Reducer Example Again export const notes = createReducer({ [UPDATE_NOTE_CONTENT]: (state, action) => state.setIn( ['byId', action.payload.noteId, 'html'], action.payload.newContent ), [SOME_OTHER_ACTION]: (state, action) => { // do something else or just return state; }), });
  • 31. Connecting Container Components import { connect } from 'react-redux'; export default connect( mapStateToProps, mapDispatchToProps, )(MainPage);
  • 32. React-Redux Mapping Functions function mapStateToProps(state) { const notesAsJS = state.notes.toJS(); return { notes: notesAsJS.ordered.map((id) => notesAsJS.byId[id]) }; } function mapDispatchToProps(dispatch) { return { onContentChange: (noteId, newContent) => dispatch(noteActions.updateNoteContent( noteId, newContent)), }; }
  • 33. Handling Asyncronous Actions β€’ Option 1: β€œSmart” actions creators. β€’ Option 2: Middleware. β€’ Option 2β€²: React Sagas.
  • 34. Smart Action Creators β€’ Call an action creator to initiate a request. β€’ The action creator emits an action to inform everyone that a request was made. β€’ The action creator makes a request. β€’ If the request succeeds, the action creator emits an action to inform everyone that a request was completed. (Same for failure and timeout.) β€’ The details of interacting with the server should be pushed into a module.
  • 35. An Example, Part 1 function makeFetchNotesAction(status, data) { return { type: FETCH_NOTES, payload: { status: status, data: data } }; }
  • 36. An Example, Part 1 export function fetchNotes() { return dispatch => { dispatch(makeFetchNotesAction('request')); return fetchData() .then(json => dispatch(makeFetchNotesAction('success', json))) .catch(error => dispatch(makeFetchNotesAction('error', error))); }; }
  • 37. Alternatively: Redux Middleware β€’ A middleware is a function that allows you to capture actions and do something before they get to the reducers. β€’ This can include things like API calls. β€’ More generally, the sky is the limit. β€’ Perhaps a little too generic for many cases.
  • 38. Alternative: Redux Sagas β€’ A middleware that works with generators. β€’ Awesome, if you understand generators. β€’ Can simplify complex workflows. β€’ Very new.
  • 39. Redux Sagas Example function* fetchNotesForStack(action) { const stackId = action.payload.stackId; yield put(getNotes.request()); const {data, error} = yield dataApi.getNotesForStack(stackId); if (!error) { yield put(getNotes.success(organizeNotes(data.notes))); } else { yield put(getNotes.failure(error)); } } function* watchFetchNotesForStack() { yield* takeEvery(SELECT_STACK, fetchNotesForStack); }
  • 40. Testing Is Easy describe('on ADD_NOTE', () => { it('should create a new note', () => { const getNoteCount = () => initialState.toJS().ordered.length; const previousCount = getNoteCount(); const newState = notesReducer(initialState, {type: ADD_NOTE}); assert.strictEqual(previousCount + 1, getNoteCount()); const newNoteId = newState.toJS().ordered[0]; const newNoteHtml = newState.getIn(['byId', newNoteId, 'html']); assert.strictEqual(newNoteHtml, 'No content'); }); });
  • 41. Caveats β€’ Its addictive. β€’ You won’t be happy using anything else. β€’ Your friends might not understand your obsession.
  • 42. THANK YOU! Yuri Takhteyev @qaramazov rangle CTO, Rangle.io Some rights reserved - Creative Commons 2.0 by-sa