Redux
for modular development
Who am I?
+10 years developing mostly in rails
but also java, js, python, php,
haskell, C++
I don’t appreciate programming
languages more than I would
appreciate a hammer.
Likes beer, guitar, business,
technology, music, learning,
dancing, F1, poker, reading, biking,
superheroes, movies, tv series,
wine, food.
@eLafo
linkedin, twitter, github...
Data
Presentation
Logic
0
0
3
3
4^4 = 256different possible global states
What are we
going to see?
Some basics we should know
How I understand a component
How do we wire components to
build a high order component -or
app with redux.
Advantages
Warnings
EXAMPLE
0
DO NOT PRESS!
1
RELEASE!
1
DO NOT PRESS!
0
DO NOT
PRESS!
DO NOT
PRESS!
0
0
DO NOT
PRESS!
Button
pressed
0
DO NOT
PRESS!
Button
pressed
0
DO NOT
PRESS!
Button
pressed
0
DO NOT
PRESS!
Button
pressed
Text: Press!
Button: green
background: red
Counter: 1
1
RELEASE!
Button
pressed
Text: Press!
Button: green
background: red
Counter: 1
1
RELEASE!
1
RELEASE!
RELEASE!
Button
released
1
Button
released
RELEASE!
1
Button
released
RELEASE!
1
Button
released
RELEASE!
1
Text: Press!
Button: green
background: red
Counter: 1
1
DO NOT
PRESS!
Button
released
Text: Press!
Button: green
background: red
Counter: 1
View
Presentation in whichever
flavour (React, Angular, JS,
JQuery...)
DO NOT
PRESS!
Presentation
Data / State
ActionCreators
(events)
1
DO NOT
PRESS!
Presentational
component
Functional
component
Actions
This should be the easy part
Button
released
Button
pressed
Managing state change
This is a new
state. The input
is copied before
doing any
change
State = f(state, action)
State = f(state, action)
Pure function Return value is only determined by
its input values, without
observable side effect
reducer.js
selectors.js
actionTypes.js
Component creator tookit
Data Data Data
Presentational
components
Functional
components
Slot for selector
State input
Slot for action creators
config.js
types.js
actions.js
Data
Data
Presentation
Logic
Presentation
Logic
Presentation
Logic
Presentation
Logic
Presentation
Logic
Presentation
Logic
Presentation
Logic
State / Data
dispatch
dispatch
dispatch
dispatch
reducers
root reducer State
reducers
root reducer State
State
reducers
root reducer
State
reducers
root reducer
State
reducers
root reducer
State
reducers
root reducer
State
reducers
root reducer
State
reducers
root reducer
State
reducers
root reducer
State
reducers
root reducer
REDUX is a library for implementing a
Design Pattern
REDUX attempts to make state
mutations predictable
Inspired by Flux, CQRS and Event
Sourcing
Redux
Principles
Single source of truth
State is read-only
Changes are made by pure
functions
Single source of
truth
Redux principles
The state of your whole application
is stored in an object tree within a
single store.
State is read-
only
Redux principles
The only way to change the state
is to emit an action, an object
describing what happened.
Changes are
made by pure
functions
Redux principles
To specify how the state tree is
transformed by actions, you write
pure reducers.
http://slides.com/jenyaterpil/redux-from-twitter-hype-to-production#/9
UI = f(state)
State = f(state, action)
Functional programming all around
actions/
todos.js
components/
todos/
TodoItem.js
...
constants/
actionTypes.js
reducers/
todos.js
index.js
rootReducer.js
todos/
components/
actions.js
actionTypes.js
constants.js
index.js
reducer.js
index.js
rootReducer.js
http://jaysoo.ca/2016/02/28/organizing-redux-application/
Can’t be that good...
Side effects
Side effects
● Turn promises into actions (one for each
state)
http://slides.com/jenyaterpil/redux-from-twitter-hype-to-production#/24
Side effects
● Turn promises into actions (one for each
state)
● Redux-thunk
http://slides.com/jenyaterpil/redux-from-twitter-hype-to-production#/9
redux-thunk
http://slides.com/jenyaterpil/redux-from-twitter-hype-to-production#/25
Side effects
● Turn promises into actions (one for each
state)
● Redux-thunk
● redux-api-middleware
http://slides.com/jenyaterpil/redux-from-twitter-hype-to-production#/9
redux-api-middleware
http://slides.com/jenyaterpil/redux-from-twitter-hype-to-production#/25
What we have
seen
Why it is so difficult to reuse code
The problem when maintaining the
state
How to think when building
components
How to wire components with redux
How Redux deals with state
A new way of thinking?
Some unmeaningful code (actions)
import * as config from './config'
const CONNECT = config.namespace + “/CONNECT”
const userIsOnline = (user) => ({
return {
type: CONNECT,
payload: user.id
}
});
import * as config form './config'
const SEND_MESSAGE = config.namespace + "/SEND_MESSAGE"
const sendMessage = (chatID, senderID, text) => ({
type: SEND_MESSAGE,
payload: {
chatID: chatID,
message: {
text: text,
status: “sent”,
timestamp: now(),
senderId: senderId,
messageId: getID()
}
}
});
Some unmeaningful code (reducers)
import * as t from './actionTypes'
const usersReducer = (state = initialState, action) =>
{
let newState = _.clone(state);
switch (action.type) {
case t.CONNECT
newState[t.payload.id].status = 'online';
return newState;
default:
return state
}
};
import * as t from './actionTypes'
const chatsReducer = (state = initialState, action) => {
let newState = _.clone(state);
switch (action.type) {
case t.SEND_MESSAGE:
newState[t.payload.chatID].messages.push(t.payload.message);
return newState;
default:
return state
}
};
Some unmeaningful code (Wiring up)
//main.js
import React from 'react';
import ReactDOM from 'react-dom';
import {Provider} from 'react-redux';
import { createStore } from 'redux';
import AppContainer from './app/containers/AppContainer';
import reducer from './rootReducer';
import injectTapEventPlugin from 'react-tap-event-plugin';
injectTapEventPlugin();
//we create the store and tell it which root reducer to use
let store = createStore(reducer);
//We create the root component and
ReactDOM.render(
<Provider store={store}>
<AppContainer />
</Provider>,
document.getElementById('app')
);
//rootReducer.js
import { combineReducers} from 'redux';
import users from './users';
import chats from './chats';
const combinedReducers = combineReducers({
[users.config.namespace] : users.reducer,
[chats.config.namespace] : chats.reducer
})
Resources and further reading
http://redux.js.org/
https://medium.com/@adamrackis/querying-a-redux-store-37db8c7f3b0f#.fua79muzx
https://scotch.io/tutorials/bookshop-with-react-redux-ii-async-requests-with-thunks
http://softwareengineering.stackexchange.com/questions/235558/what-is-state-mutable-state-and-immutable-state
https://daveceddia.com/timeline-for-learning-react/
http://www.yegor256.com/2016/08/15/what-is-wrong-object-oriented-programming.html
https://datarockets.com/blog/redux-structure
http://jpsierens.com/tutorial-react-redux-webpack/
https://www.sitepoint.com/how-to-build-a-todo-app-using-react-redux-and-immutable-js/
http://jaysoo.ca/2016/02/28/organizing-redux-application/
Resources and further reading
http://es.slideshare.net/nikgraf/react-redux-introduction
http://es.slideshare.net/benlesh1/async-redux-actions-with-rxjs-react-rally-2016
http://es.slideshare.net/nirkaufman/redux-with-angular-2-workshop-2016
http://es.slideshare.net/fdaciuk/designing-applications-with-redux
http://es.slideshare.net/FDConf/redux-from-twitter-hype-to-production-61102006
http://es.slideshare.net/justingordon/react-on-rails-v4032
http://es.slideshare.net/rolandkuhn/reactive-streams
Thank you!!!
http://aspcamp.aspgems.com

Modular development with redux

Editor's Notes

  • #3 No le tengo aprecio a ningún lenguaje. Me metí en esto porque me gusta resolver problemas, así que no esperéis ver código
  • #4 Esto es un caso de estudio. Estoy buscando formas diferentes de desarrollar. Machine learning, datos y event sourcing, ethereum
  • #5 En qué se traduce el beneficio de la reuitilizacion? En tiempo para…
  • #10 Y para reutilizar deberíamos estar trabajando con piezas como estas.
  • #11 Pero demasiadas veces nos quedamos aquí.
  • #12 Por qué pasa esto? Porque nos han enseñado que había que tener tres abstracciones. Y eso mola
  • #13 Y lo pusimos en práctica con el patrón mvc Y es un patrón que funciona muy bien
  • #14 Para esto. Pero a medida que la tecnología avanzaba (angular, react…) nos vinimos arriba y empezamos a hacer cosas
  • #15 Como esta (tiempo real, dashboards, interfaces complicadas)
  • #16 Y empezaron los problemas. Modelos con modelos vistas con mas de un modelo. Modelos que participan en dos vistas… los controladores ahí viendo la orgía que no controlaban nada. Así que un día que te levantas como optimista. En plan me voy a comer el mundo y decides que vas a refactorizar
  • #17 Y esto por qué pasa? Habéis oído alguna vez hablar sobre el problema de mantener el estado?
  • #20 Y somos incapaces por naturaleza de gestionar eso
  • #22 Porque tenemos 7 slots. Así que hacemos cosas que terminan fallando. Y cuando empezamos a debiguear pasan cosas como que tocas en un sitio y se rompe aquello
  • #23 Y como lo solucionamos? Dibujando porque así es mucho mas fácil.
  • #24 Viene de bbdd .nos hemos adaptado a la máquina en lugar de hacer que la máquina nos entienda a nosotros. Porque nosotros no pensamos así. Pensamos en grafos. Poner slide de grafo
  • #25 Y esto es ungrafo
  • #26 Pero es que no nos bastaba con esto.cabtidad posibles de estados. Y un estado muy distribuido.Sino que encima dejamos que toque todo dios.
  • #30 Un ejemplo de un componente
  • #33 Vamos a ver cómo lo soluciona redux
  • #47 Tenemos tres componentes principales
  • #50 Smart y dumb components
  • #51 Quitar el tachado
  • #58 Quitar initialstate y actions
  • #62 Poner cuadrados. Cada cuadrado es un directorio o un fichero
  • #63 Map reduce?
  • #66 Que hacemos con la capa de datos? Es donde idealmente en un futuro deberíamos desarrollar. Integrando datos.
  • #69 Cambiar esta diapo y poner una toma de enchufe
  • #70 Cambiar esta diapo y poner una toma de enchufe
  • #71 Cambiar esta diapo y poner una toma de enchufe
  • #72 Cambiar esta diapo y poner una toma de enchufe
  • #76 A nosotros decidimos que parte del árbol va a cada reduce e. Porque el root reduce e es mio
  • #81 Map reduce