SlideShare a Scribd company logo
REDUX
DASER DAVID - NHUB
REDUX - ACTION
- Actions are payloads of information that send
data from your application to your store.
- They are the only source of information for the
store.
- You send them to the store using store.dispatch().
REDUX - ACTION
NOTE: PAY CLOSE ATTENTION TO
store.dispatch()
IT IS USED WHEN SENDING ACTION TO STORES.
REDUX - ACTION
const ADD_TODO = 'ADD_TODO'
{
type: ADD_TODO,
text: 'Build my first Redux app'
}
NOTE: type is a must, you can add other things provided you meet
the type requirements.
REDUX - ACTION
- Actions are plain JavaScript objects.
- Actions must have a type property that indicates the type
of action being performed.
- Types should typically be defined as string constants.
- Once your app is large enough, you may want to move them
into a separate module.
REDUX - ACTION
import { ADD_TODO, REMOVE_TODO } from '../actionTypes'
../actionTypes.JS
export const ADD_TODO = 'ADD_TODO'
export const REMOVE_TODO = 'REMOVE_TODO'
REDUX - ACTION - ACTION CREATORS
Action creators are exactly that—functions that
create actions.
It's easy to conflate the terms “action” and “action
creator,” so do your best to use the proper term.
EXERCISE 1
- CONSTRUCT AN ACTION
- CONSTRUCT AN ACTION CREATOR
REDUX - ACTION - ACTION CREATORS
//ACTION
export const ADD_TODO = 'ADD_TODO'
//ACTION CREATOR
export function addTodo(text)
{
return { type: ADD_TODO, text }
}
REDUX - REDUCERS
- Reducers specify how the application's state
changes in response to actions sent to the store.
- Remember that actions only describe the fact that
something happened, but don't describe how the
application's state changes.
REDUX - REDUCERS
The reducer is a pure function that takes the previous state and
an action, and returns the next state.
(previousState, action) => newState
REDUX - REDUCERS
PURE FUNCTION
function priceAfterTax(productPrice) {
return (productPrice * 0.20) + productPrice;
}
REDUX - REDUCERS
IMPURE
var tax = 20;
function calculateTax(productPrice) {
return (productPrice * (tax/100)) + productPrice;
}
REDUX - REDUCERS
Things you should never do inside a reducer:
- Mutate its arguments;
- Perform side effects like API calls and routing transitions;
- Call non-pure functions, e.g. Date.now() or Math.random().
REDUX - REDUCERS
Given the same arguments, it should calculate the
next state and return it.
- No surprises.
- No side effects.
- No API calls.
- No mutations.
- Just a calculation.
LETS WALK DOWN SOME DEEP
actions.js
export const VisibilityFilters = {
SHOW_ALL: 'SHOW_ALL',
SHOW_COMPLETED: 'SHOW_COMPLETED',
SHOW_ACTIVE: 'SHOW_ACTIVE'
}
We'll start by specifying the initial state.
Redux will call our reducer with an undefined state
for the first time.
This is our chance to return the initial state of our
app.
ALWAYS HAVE AN INITIAL STATE IN MIND
import { VisibilityFilters } from './actions'
const initialState = {
visibilityFilter: VisibilityFilters.SHOW_ALL,
todos: []
}
function todoApp(state, action) {
if (typeof state === 'undefined') {
return initialState
}
return state
}
function todoApp(state = initialState,
action) {
// For now, don't handle any actions
// and just return the state given to us.
return state
}
Object.assign()
Object.assign(target, ...sources)
Parameters
Target
The target object.
Sources
The source object(s).
Return value
The target object.
Cloning
var obj = { a: 1 };
var copy = Object.assign({}, obj);
console.log(copy); // { a: 1 }
function todoApp(state = initialState, action) {
switch (action.type) {
case SET_VISIBILITY_FILTER:
return Object.assign({}, state, {
visibilityFilter: action.filter
})
default:
return state
}
NOTE:
1. We don't mutate the state.
- We create a copy with Object.assign().
- Object.assign(state, { visibilityFilter: action.filter }) is also wrong: it will
mutate the first argument.
- You must supply an empty object as the first parameter.
- You can also enable the object spread operator proposal to write { ...state,
...newState } instead.
2. We return the previous state in the default case. It's important to return
the previous state for any unknown action.
LETS SEE THE ACTION?
export function setVisibilityFilter(filter) {
return { type: SET_VISIBILITY_FILTER, filter }
}
GOING DEEPER - REDUCER
case ADD_TODO:
return Object.assign({}, state, {
todos: [
...state.todos,
{
text: action.text,
completed: false
} ]
})
GOING DEEPER - ACTION
export function addTodo(text) {
return { type: ADD_TODO, text }
}
PROBLEMS AT SCALE
When the app is larger, we can split the reducers into
separate files and keep them completely independent and
managing different data domains.
SOLUTION:
- Redux provides a utility called combineReducers()
- All combineReducers() does is generate a function
that calls your reducers with the slices of state
selected according to their keys, and combining their
results into a single object again.
REDUX - STORE
we defined the actions that represent the facts
about “what happened” and the reducers that
update the state according to those actions.
The Store is the object that brings them together.
REDUX - STORE
The store has the following responsibilities:
- Holds application state;
- Allows access to state via getState();
- Allows state to be updated via dispatch(action);
- Registers listeners via subscribe(listener);
- Handles unregistering of listeners via the function returned by
subscribe(listener).
REDUX - STORE
It's important to note that you'll only have a single
store in a Redux application.
REDUX - STORE
- It's easy to create a store if you have a reducer.
- We used combineReducers() to combine several
reducers into one.
- We will now import it, and pass it to
createStore().
REDUX - STORE
import { createStore } from 'redux'
import todoApp from './reducers'
let store = createStore(todoApp)
REDUX - STORE
You may optionally specify the initial state as the second
argument to createStore(). This is useful for hydrating the state of
the client to match the state of a Redux application running on the
server.
let store = createStore(todoApp,
window.STATE_FROM_SERVER)
Dispatching Actions
store.dispatch(addTodo('Learn about actions'))
DATA FLOW
Redux architecture revolves around a strict unidirectional
data flow.
This means that all data in an application follows the same
lifecycle pattern, making the logic of your app more
predictable and easier to understand. It also encourages
data normalization, so that you don't end up with multiple,
independent copies of the same data that are unaware of
one another.
DATA FLOW - 4 STEPS OF REDUX
1. You call store.dispatch(action).
An action is a plain object describing what happened. For example:
{ type: 'LIKE_ARTICLE', articleId: 42 }
{ type: 'FETCH_USER_SUCCESS', response: { id: 3, name: 'Mary' } }
{ type: 'ADD_TODO', text: 'Read the Redux docs.' }
Think of an action as a very brief snippet of news. “Mary liked article 42.” or “‘Read the Redux docs.' was
added to the list of todos.”
You can call store.dispatch(action) from anywhere in your app, including components and XHR callbacks,
or even at scheduled intervals.
DATA FLOW - 4 STEPS OF REDUX
2. The Redux store calls the reducer function you gave it.
The store will pass two arguments to the reducer: the current state
tree and the action. For example, in the todo app, the root reducer
might receive something like this:
let previousState = {
visibleTodoFilter: 'SHOW_ALL',
todos: [
{
text: 'Read the docs.',
complete: false
}
]
}
// The action being performed (adding a todo)
let action = {
type: 'ADD_TODO',
text: 'Understand the flow.'
}
// Your reducer returns the next application state
let nextState = todoApp(previousState, action)
DATA FLOW - 4 STEPS OF REDUX
3. The root reducer may combine the output of multiple reducers into a
single state tree.
REMEMBER
How you structure the root reducer is completely up to you. Redux ships with
a combineReducers() helper function, useful for “splitting” the root reducer
into separate functions that each manage one branch of the state tree.
function todos(state = [], action) {
// Somehow calculate it...
return nextState
}
function visibleTodoFilter(state = 'SHOW_ALL', action) {
// Somehow calculate it...
return nextState
}
let todoApp = combineReducers({
todos,
visibleTodoFilter
})
When you emit an action, todoApp returned by combineReducers will call both reducers:
let nextTodos = todos(state.todos, action)
let nextVisibleTodoFilter = visibleTodoFilter(state.visibleTodoFilter, action)
It will then combine both sets of results into a single state tree:
return {
todos: nextTodos,
visibleTodoFilter: nextVisibleTodoFilter
}
While combineReducers() is a handy helper utility, you don't have to use it; feel free to write your
own root reducer!
DATA FLOW - 4 STEPS OF REDUX
4. The Redux store saves the complete state tree returned by the root
reducer.
This new tree is now the next state of your app! Every listener
registered with store.subscribe(listener) will now be invoked; listeners
may call store.getState() to get the current state.
Now, the UI can be updated to reflect the new state. If you use bindings
like React Redux, this is the point at which
component.setState(newState) is called.
THANK YOU….

More Related Content

What's hot

React & Redux
React & ReduxReact & Redux
React & Redux
Federico Bond
 
React js programming concept
React js programming conceptReact js programming concept
React js programming concept
Tariqul islam
 
react redux.pdf
react redux.pdfreact redux.pdf
react redux.pdf
Knoldus Inc.
 
React Hooks
React HooksReact Hooks
React Hooks
Erez Cohen
 
Reactjs
Reactjs Reactjs
Reactjs
Neha Sharma
 
ReactJs
ReactJsReactJs
React state managmenet with Redux
React state managmenet with ReduxReact state managmenet with Redux
React state managmenet with Redux
Vedran Blaženka
 
Redux Toolkit - Quick Intro - 2022
Redux Toolkit - Quick Intro - 2022Redux Toolkit - Quick Intro - 2022
Redux Toolkit - Quick Intro - 2022
Fabio Biondi
 
Introduction to React JS for beginners | Namespace IT
Introduction to React JS for beginners | Namespace ITIntroduction to React JS for beginners | Namespace IT
Introduction to React JS for beginners | Namespace IT
namespaceit
 
Ngrx: Redux in angular
Ngrx: Redux in angularNgrx: Redux in angular
Ngrx: Redux in angular
Saadnoor Salehin
 
React workshop
React workshopReact workshop
React workshop
Imran Sayed
 
An introduction to React.js
An introduction to React.jsAn introduction to React.js
An introduction to React.js
Emanuele DelBono
 
Its time to React.js
Its time to React.jsIts time to React.js
Its time to React.js
Ritesh Mehrotra
 
Introduction to react_js
Introduction to react_jsIntroduction to react_js
Introduction to react_js
MicroPyramid .
 
ReactJS presentation
ReactJS presentationReactJS presentation
ReactJS presentation
Thanh Tuong
 
An Introduction to Redux
An Introduction to ReduxAn Introduction to Redux
An Introduction to Redux
NexThoughts Technologies
 
React js
React jsReact js
React js
Alireza Akbari
 
Introduction to React
Introduction to ReactIntroduction to React
Introduction to React
Rob Quick
 
Introduction to ReactJS
Introduction to ReactJSIntroduction to ReactJS
Introduction to ReactJS
Knoldus Inc.
 

What's hot (20)

React & Redux
React & ReduxReact & Redux
React & Redux
 
React js programming concept
React js programming conceptReact js programming concept
React js programming concept
 
react redux.pdf
react redux.pdfreact redux.pdf
react redux.pdf
 
React Hooks
React HooksReact Hooks
React Hooks
 
Reactjs
Reactjs Reactjs
Reactjs
 
ReactJs
ReactJsReactJs
ReactJs
 
React state managmenet with Redux
React state managmenet with ReduxReact state managmenet with Redux
React state managmenet with Redux
 
Redux Toolkit - Quick Intro - 2022
Redux Toolkit - Quick Intro - 2022Redux Toolkit - Quick Intro - 2022
Redux Toolkit - Quick Intro - 2022
 
Introduction to React JS for beginners | Namespace IT
Introduction to React JS for beginners | Namespace ITIntroduction to React JS for beginners | Namespace IT
Introduction to React JS for beginners | Namespace IT
 
Ngrx: Redux in angular
Ngrx: Redux in angularNgrx: Redux in angular
Ngrx: Redux in angular
 
React workshop
React workshopReact workshop
React workshop
 
An introduction to React.js
An introduction to React.jsAn introduction to React.js
An introduction to React.js
 
React JS - Introduction
React JS - IntroductionReact JS - Introduction
React JS - Introduction
 
Its time to React.js
Its time to React.jsIts time to React.js
Its time to React.js
 
Introduction to react_js
Introduction to react_jsIntroduction to react_js
Introduction to react_js
 
ReactJS presentation
ReactJS presentationReactJS presentation
ReactJS presentation
 
An Introduction to Redux
An Introduction to ReduxAn Introduction to Redux
An Introduction to Redux
 
React js
React jsReact js
React js
 
Introduction to React
Introduction to ReactIntroduction to React
Introduction to React
 
Introduction to ReactJS
Introduction to ReactJSIntroduction to ReactJS
Introduction to ReactJS
 

Similar to Redux training

Getting started with Redux js
Getting started with Redux jsGetting started with Redux js
Getting started with Redux js
Citrix
 
How to use redux with react hooks in react native application
How to use redux with react hooks in react native applicationHow to use redux with react hooks in react native application
How to use redux with react hooks in react native application
Katy Slemon
 
Maintaining sanity in a large redux app
Maintaining sanity in a large redux appMaintaining sanity in a large redux app
Maintaining sanity in a large redux app
Nitish Kumar
 
Understanding redux
Understanding reduxUnderstanding redux
Understanding redux
David Atchley
 
The evolution of redux action creators
The evolution of redux action creatorsThe evolution of redux action creators
The evolution of redux action creators
George Bukhanov
 
Workshop 20: ReactJS Part II Flux Pattern & Redux
Workshop 20: ReactJS Part II Flux Pattern & ReduxWorkshop 20: ReactJS Part II Flux Pattern & Redux
Workshop 20: ReactJS Part II Flux Pattern & Redux
Visual Engineering
 
React redux
React reduxReact redux
React redux
Michel Perez
 
Reactive.architecture.with.Angular
Reactive.architecture.with.AngularReactive.architecture.with.Angular
Reactive.architecture.with.AngularEvan Schultz
 
Reactивная тяга
Reactивная тягаReactивная тяга
Reactивная тяга
Vitebsk Miniq
 
Redux with angular 2 - workshop 2016
Redux with angular 2 - workshop 2016Redux with angular 2 - workshop 2016
Redux with angular 2 - workshop 2016
Nir Kaufman
 
Ngrx slides
Ngrx slidesNgrx slides
Ngrx slides
Christoffer Noring
 
React lecture
React lectureReact lecture
React lecture
Christoffer Noring
 
State of the state
State of the stateState of the state
State of the state
Anton Korzunov
 
From mvc to redux: 停看聽
From mvc to redux: 停看聽From mvc to redux: 停看聽
From mvc to redux: 停看聽
Jeff Lin
 
Introduction to Redux (for Angular and React devs)
Introduction to Redux (for Angular and React devs)Introduction to Redux (for Angular and React devs)
Introduction to Redux (for Angular and React devs)
Fabio Biondi
 
Intro to Redux | DreamLab Academy #3
Intro to Redux | DreamLab Academy #3 Intro to Redux | DreamLab Academy #3
Intro to Redux | DreamLab Academy #3
DreamLab
 
Manage the Flux of your Web Application: Let's Redux
Manage the Flux of your Web Application: Let's ReduxManage the Flux of your Web Application: Let's Redux
Manage the Flux of your Web Application: Let's Redux
Commit University
 
Redux
ReduxRedux
React + Redux. Best practices
React + Redux.  Best practicesReact + Redux.  Best practices
React + Redux. Best practices
Clickky
 
State manager in Vue.js, from zero to Vuex
State manager in Vue.js, from zero to VuexState manager in Vue.js, from zero to Vuex
State manager in Vue.js, from zero to Vuex
Commit University
 

Similar to Redux training (20)

Getting started with Redux js
Getting started with Redux jsGetting started with Redux js
Getting started with Redux js
 
How to use redux with react hooks in react native application
How to use redux with react hooks in react native applicationHow to use redux with react hooks in react native application
How to use redux with react hooks in react native application
 
Maintaining sanity in a large redux app
Maintaining sanity in a large redux appMaintaining sanity in a large redux app
Maintaining sanity in a large redux app
 
Understanding redux
Understanding reduxUnderstanding redux
Understanding redux
 
The evolution of redux action creators
The evolution of redux action creatorsThe evolution of redux action creators
The evolution of redux action creators
 
Workshop 20: ReactJS Part II Flux Pattern & Redux
Workshop 20: ReactJS Part II Flux Pattern & ReduxWorkshop 20: ReactJS Part II Flux Pattern & Redux
Workshop 20: ReactJS Part II Flux Pattern & Redux
 
React redux
React reduxReact redux
React redux
 
Reactive.architecture.with.Angular
Reactive.architecture.with.AngularReactive.architecture.with.Angular
Reactive.architecture.with.Angular
 
Reactивная тяга
Reactивная тягаReactивная тяга
Reactивная тяга
 
Redux with angular 2 - workshop 2016
Redux with angular 2 - workshop 2016Redux with angular 2 - workshop 2016
Redux with angular 2 - workshop 2016
 
Ngrx slides
Ngrx slidesNgrx slides
Ngrx slides
 
React lecture
React lectureReact lecture
React lecture
 
State of the state
State of the stateState of the state
State of the state
 
From mvc to redux: 停看聽
From mvc to redux: 停看聽From mvc to redux: 停看聽
From mvc to redux: 停看聽
 
Introduction to Redux (for Angular and React devs)
Introduction to Redux (for Angular and React devs)Introduction to Redux (for Angular and React devs)
Introduction to Redux (for Angular and React devs)
 
Intro to Redux | DreamLab Academy #3
Intro to Redux | DreamLab Academy #3 Intro to Redux | DreamLab Academy #3
Intro to Redux | DreamLab Academy #3
 
Manage the Flux of your Web Application: Let's Redux
Manage the Flux of your Web Application: Let's ReduxManage the Flux of your Web Application: Let's Redux
Manage the Flux of your Web Application: Let's Redux
 
Redux
ReduxRedux
Redux
 
React + Redux. Best practices
React + Redux.  Best practicesReact + Redux.  Best practices
React + Redux. Best practices
 
State manager in Vue.js, from zero to Vuex
State manager in Vue.js, from zero to VuexState manager in Vue.js, from zero to Vuex
State manager in Vue.js, from zero to Vuex
 

Recently uploaded

Cosmetic shop management system project report.pdf
Cosmetic shop management system project report.pdfCosmetic shop management system project report.pdf
Cosmetic shop management system project report.pdf
Kamal Acharya
 
Standard Reomte Control Interface - Neometrix
Standard Reomte Control Interface - NeometrixStandard Reomte Control Interface - Neometrix
Standard Reomte Control Interface - Neometrix
Neometrix_Engineering_Pvt_Ltd
 
Gen AI Study Jams _ For the GDSC Leads in India.pdf
Gen AI Study Jams _ For the GDSC Leads in India.pdfGen AI Study Jams _ For the GDSC Leads in India.pdf
Gen AI Study Jams _ For the GDSC Leads in India.pdf
gdsczhcet
 
WATER CRISIS and its solutions-pptx 1234
WATER CRISIS and its solutions-pptx 1234WATER CRISIS and its solutions-pptx 1234
WATER CRISIS and its solutions-pptx 1234
AafreenAbuthahir2
 
Governing Equations for Fundamental Aerodynamics_Anderson2010.pdf
Governing Equations for Fundamental Aerodynamics_Anderson2010.pdfGoverning Equations for Fundamental Aerodynamics_Anderson2010.pdf
Governing Equations for Fundamental Aerodynamics_Anderson2010.pdf
WENKENLI1
 
CME397 Surface Engineering- Professional Elective
CME397 Surface Engineering- Professional ElectiveCME397 Surface Engineering- Professional Elective
CME397 Surface Engineering- Professional Elective
karthi keyan
 
DESIGN A COTTON SEED SEPARATION MACHINE.docx
DESIGN A COTTON SEED SEPARATION MACHINE.docxDESIGN A COTTON SEED SEPARATION MACHINE.docx
DESIGN A COTTON SEED SEPARATION MACHINE.docx
FluxPrime1
 
Industrial Training at Shahjalal Fertilizer Company Limited (SFCL)
Industrial Training at Shahjalal Fertilizer Company Limited (SFCL)Industrial Training at Shahjalal Fertilizer Company Limited (SFCL)
Industrial Training at Shahjalal Fertilizer Company Limited (SFCL)
MdTanvirMahtab2
 
space technology lecture notes on satellite
space technology lecture notes on satellitespace technology lecture notes on satellite
space technology lecture notes on satellite
ongomchris
 
Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&BDesign and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
Sreedhar Chowdam
 
H.Seo, ICLR 2024, MLILAB, KAIST AI.pdf
H.Seo,  ICLR 2024, MLILAB,  KAIST AI.pdfH.Seo,  ICLR 2024, MLILAB,  KAIST AI.pdf
H.Seo, ICLR 2024, MLILAB, KAIST AI.pdf
MLILAB
 
Hybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdf
Hybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdfHybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdf
Hybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdf
fxintegritypublishin
 
ethical hacking-mobile hacking methods.ppt
ethical hacking-mobile hacking methods.pptethical hacking-mobile hacking methods.ppt
ethical hacking-mobile hacking methods.ppt
Jayaprasanna4
 
Immunizing Image Classifiers Against Localized Adversary Attacks
Immunizing Image Classifiers Against Localized Adversary AttacksImmunizing Image Classifiers Against Localized Adversary Attacks
Immunizing Image Classifiers Against Localized Adversary Attacks
gerogepatton
 
Sachpazis:Terzaghi Bearing Capacity Estimation in simple terms with Calculati...
Sachpazis:Terzaghi Bearing Capacity Estimation in simple terms with Calculati...Sachpazis:Terzaghi Bearing Capacity Estimation in simple terms with Calculati...
Sachpazis:Terzaghi Bearing Capacity Estimation in simple terms with Calculati...
Dr.Costas Sachpazis
 
road safety engineering r s e unit 3.pdf
road safety engineering  r s e unit 3.pdfroad safety engineering  r s e unit 3.pdf
road safety engineering r s e unit 3.pdf
VENKATESHvenky89705
 
一比一原版(UofT毕业证)多伦多大学毕业证成绩单如何办理
一比一原版(UofT毕业证)多伦多大学毕业证成绩单如何办理一比一原版(UofT毕业证)多伦多大学毕业证成绩单如何办理
一比一原版(UofT毕业证)多伦多大学毕业证成绩单如何办理
ydteq
 
CFD Simulation of By-pass Flow in a HRSG module by R&R Consult.pptx
CFD Simulation of By-pass Flow in a HRSG module by R&R Consult.pptxCFD Simulation of By-pass Flow in a HRSG module by R&R Consult.pptx
CFD Simulation of By-pass Flow in a HRSG module by R&R Consult.pptx
R&R Consult
 
ML for identifying fraud using open blockchain data.pptx
ML for identifying fraud using open blockchain data.pptxML for identifying fraud using open blockchain data.pptx
ML for identifying fraud using open blockchain data.pptx
Vijay Dialani, PhD
 
AP LAB PPT.pdf ap lab ppt no title specific
AP LAB PPT.pdf ap lab ppt no title specificAP LAB PPT.pdf ap lab ppt no title specific
AP LAB PPT.pdf ap lab ppt no title specific
BrazilAccount1
 

Recently uploaded (20)

Cosmetic shop management system project report.pdf
Cosmetic shop management system project report.pdfCosmetic shop management system project report.pdf
Cosmetic shop management system project report.pdf
 
Standard Reomte Control Interface - Neometrix
Standard Reomte Control Interface - NeometrixStandard Reomte Control Interface - Neometrix
Standard Reomte Control Interface - Neometrix
 
Gen AI Study Jams _ For the GDSC Leads in India.pdf
Gen AI Study Jams _ For the GDSC Leads in India.pdfGen AI Study Jams _ For the GDSC Leads in India.pdf
Gen AI Study Jams _ For the GDSC Leads in India.pdf
 
WATER CRISIS and its solutions-pptx 1234
WATER CRISIS and its solutions-pptx 1234WATER CRISIS and its solutions-pptx 1234
WATER CRISIS and its solutions-pptx 1234
 
Governing Equations for Fundamental Aerodynamics_Anderson2010.pdf
Governing Equations for Fundamental Aerodynamics_Anderson2010.pdfGoverning Equations for Fundamental Aerodynamics_Anderson2010.pdf
Governing Equations for Fundamental Aerodynamics_Anderson2010.pdf
 
CME397 Surface Engineering- Professional Elective
CME397 Surface Engineering- Professional ElectiveCME397 Surface Engineering- Professional Elective
CME397 Surface Engineering- Professional Elective
 
DESIGN A COTTON SEED SEPARATION MACHINE.docx
DESIGN A COTTON SEED SEPARATION MACHINE.docxDESIGN A COTTON SEED SEPARATION MACHINE.docx
DESIGN A COTTON SEED SEPARATION MACHINE.docx
 
Industrial Training at Shahjalal Fertilizer Company Limited (SFCL)
Industrial Training at Shahjalal Fertilizer Company Limited (SFCL)Industrial Training at Shahjalal Fertilizer Company Limited (SFCL)
Industrial Training at Shahjalal Fertilizer Company Limited (SFCL)
 
space technology lecture notes on satellite
space technology lecture notes on satellitespace technology lecture notes on satellite
space technology lecture notes on satellite
 
Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&BDesign and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
 
H.Seo, ICLR 2024, MLILAB, KAIST AI.pdf
H.Seo,  ICLR 2024, MLILAB,  KAIST AI.pdfH.Seo,  ICLR 2024, MLILAB,  KAIST AI.pdf
H.Seo, ICLR 2024, MLILAB, KAIST AI.pdf
 
Hybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdf
Hybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdfHybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdf
Hybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdf
 
ethical hacking-mobile hacking methods.ppt
ethical hacking-mobile hacking methods.pptethical hacking-mobile hacking methods.ppt
ethical hacking-mobile hacking methods.ppt
 
Immunizing Image Classifiers Against Localized Adversary Attacks
Immunizing Image Classifiers Against Localized Adversary AttacksImmunizing Image Classifiers Against Localized Adversary Attacks
Immunizing Image Classifiers Against Localized Adversary Attacks
 
Sachpazis:Terzaghi Bearing Capacity Estimation in simple terms with Calculati...
Sachpazis:Terzaghi Bearing Capacity Estimation in simple terms with Calculati...Sachpazis:Terzaghi Bearing Capacity Estimation in simple terms with Calculati...
Sachpazis:Terzaghi Bearing Capacity Estimation in simple terms with Calculati...
 
road safety engineering r s e unit 3.pdf
road safety engineering  r s e unit 3.pdfroad safety engineering  r s e unit 3.pdf
road safety engineering r s e unit 3.pdf
 
一比一原版(UofT毕业证)多伦多大学毕业证成绩单如何办理
一比一原版(UofT毕业证)多伦多大学毕业证成绩单如何办理一比一原版(UofT毕业证)多伦多大学毕业证成绩单如何办理
一比一原版(UofT毕业证)多伦多大学毕业证成绩单如何办理
 
CFD Simulation of By-pass Flow in a HRSG module by R&R Consult.pptx
CFD Simulation of By-pass Flow in a HRSG module by R&R Consult.pptxCFD Simulation of By-pass Flow in a HRSG module by R&R Consult.pptx
CFD Simulation of By-pass Flow in a HRSG module by R&R Consult.pptx
 
ML for identifying fraud using open blockchain data.pptx
ML for identifying fraud using open blockchain data.pptxML for identifying fraud using open blockchain data.pptx
ML for identifying fraud using open blockchain data.pptx
 
AP LAB PPT.pdf ap lab ppt no title specific
AP LAB PPT.pdf ap lab ppt no title specificAP LAB PPT.pdf ap lab ppt no title specific
AP LAB PPT.pdf ap lab ppt no title specific
 

Redux training

  • 2. REDUX - ACTION - Actions are payloads of information that send data from your application to your store. - They are the only source of information for the store. - You send them to the store using store.dispatch().
  • 3. REDUX - ACTION NOTE: PAY CLOSE ATTENTION TO store.dispatch() IT IS USED WHEN SENDING ACTION TO STORES.
  • 4. REDUX - ACTION const ADD_TODO = 'ADD_TODO' { type: ADD_TODO, text: 'Build my first Redux app' } NOTE: type is a must, you can add other things provided you meet the type requirements.
  • 5. REDUX - ACTION - Actions are plain JavaScript objects. - Actions must have a type property that indicates the type of action being performed. - Types should typically be defined as string constants. - Once your app is large enough, you may want to move them into a separate module.
  • 6. REDUX - ACTION import { ADD_TODO, REMOVE_TODO } from '../actionTypes' ../actionTypes.JS export const ADD_TODO = 'ADD_TODO' export const REMOVE_TODO = 'REMOVE_TODO'
  • 7. REDUX - ACTION - ACTION CREATORS Action creators are exactly that—functions that create actions. It's easy to conflate the terms “action” and “action creator,” so do your best to use the proper term.
  • 8. EXERCISE 1 - CONSTRUCT AN ACTION - CONSTRUCT AN ACTION CREATOR
  • 9. REDUX - ACTION - ACTION CREATORS //ACTION export const ADD_TODO = 'ADD_TODO' //ACTION CREATOR export function addTodo(text) { return { type: ADD_TODO, text } }
  • 10. REDUX - REDUCERS - Reducers specify how the application's state changes in response to actions sent to the store. - Remember that actions only describe the fact that something happened, but don't describe how the application's state changes.
  • 11. REDUX - REDUCERS The reducer is a pure function that takes the previous state and an action, and returns the next state. (previousState, action) => newState
  • 12. REDUX - REDUCERS PURE FUNCTION function priceAfterTax(productPrice) { return (productPrice * 0.20) + productPrice; }
  • 13. REDUX - REDUCERS IMPURE var tax = 20; function calculateTax(productPrice) { return (productPrice * (tax/100)) + productPrice; }
  • 14. REDUX - REDUCERS Things you should never do inside a reducer: - Mutate its arguments; - Perform side effects like API calls and routing transitions; - Call non-pure functions, e.g. Date.now() or Math.random().
  • 15. REDUX - REDUCERS Given the same arguments, it should calculate the next state and return it. - No surprises. - No side effects. - No API calls. - No mutations. - Just a calculation.
  • 16. LETS WALK DOWN SOME DEEP actions.js export const VisibilityFilters = { SHOW_ALL: 'SHOW_ALL', SHOW_COMPLETED: 'SHOW_COMPLETED', SHOW_ACTIVE: 'SHOW_ACTIVE' }
  • 17. We'll start by specifying the initial state. Redux will call our reducer with an undefined state for the first time. This is our chance to return the initial state of our app. ALWAYS HAVE AN INITIAL STATE IN MIND
  • 18. import { VisibilityFilters } from './actions' const initialState = { visibilityFilter: VisibilityFilters.SHOW_ALL, todos: [] }
  • 19. function todoApp(state, action) { if (typeof state === 'undefined') { return initialState } return state }
  • 20. function todoApp(state = initialState, action) { // For now, don't handle any actions // and just return the state given to us. return state }
  • 21. Object.assign() Object.assign(target, ...sources) Parameters Target The target object. Sources The source object(s). Return value The target object.
  • 22. Cloning var obj = { a: 1 }; var copy = Object.assign({}, obj); console.log(copy); // { a: 1 }
  • 23. function todoApp(state = initialState, action) { switch (action.type) { case SET_VISIBILITY_FILTER: return Object.assign({}, state, { visibilityFilter: action.filter }) default: return state }
  • 24. NOTE: 1. We don't mutate the state. - We create a copy with Object.assign(). - Object.assign(state, { visibilityFilter: action.filter }) is also wrong: it will mutate the first argument. - You must supply an empty object as the first parameter. - You can also enable the object spread operator proposal to write { ...state, ...newState } instead. 2. We return the previous state in the default case. It's important to return the previous state for any unknown action.
  • 25. LETS SEE THE ACTION? export function setVisibilityFilter(filter) { return { type: SET_VISIBILITY_FILTER, filter } }
  • 26. GOING DEEPER - REDUCER case ADD_TODO: return Object.assign({}, state, { todos: [ ...state.todos, { text: action.text, completed: false } ] })
  • 27. GOING DEEPER - ACTION export function addTodo(text) { return { type: ADD_TODO, text } }
  • 28. PROBLEMS AT SCALE When the app is larger, we can split the reducers into separate files and keep them completely independent and managing different data domains.
  • 29. SOLUTION: - Redux provides a utility called combineReducers() - All combineReducers() does is generate a function that calls your reducers with the slices of state selected according to their keys, and combining their results into a single object again.
  • 30. REDUX - STORE we defined the actions that represent the facts about “what happened” and the reducers that update the state according to those actions. The Store is the object that brings them together.
  • 31. REDUX - STORE The store has the following responsibilities: - Holds application state; - Allows access to state via getState(); - Allows state to be updated via dispatch(action); - Registers listeners via subscribe(listener); - Handles unregistering of listeners via the function returned by subscribe(listener).
  • 32. REDUX - STORE It's important to note that you'll only have a single store in a Redux application.
  • 33. REDUX - STORE - It's easy to create a store if you have a reducer. - We used combineReducers() to combine several reducers into one. - We will now import it, and pass it to createStore().
  • 34. REDUX - STORE import { createStore } from 'redux' import todoApp from './reducers' let store = createStore(todoApp)
  • 35. REDUX - STORE You may optionally specify the initial state as the second argument to createStore(). This is useful for hydrating the state of the client to match the state of a Redux application running on the server. let store = createStore(todoApp, window.STATE_FROM_SERVER)
  • 37. DATA FLOW Redux architecture revolves around a strict unidirectional data flow. This means that all data in an application follows the same lifecycle pattern, making the logic of your app more predictable and easier to understand. It also encourages data normalization, so that you don't end up with multiple, independent copies of the same data that are unaware of one another.
  • 38. DATA FLOW - 4 STEPS OF REDUX 1. You call store.dispatch(action). An action is a plain object describing what happened. For example: { type: 'LIKE_ARTICLE', articleId: 42 } { type: 'FETCH_USER_SUCCESS', response: { id: 3, name: 'Mary' } } { type: 'ADD_TODO', text: 'Read the Redux docs.' } Think of an action as a very brief snippet of news. “Mary liked article 42.” or “‘Read the Redux docs.' was added to the list of todos.” You can call store.dispatch(action) from anywhere in your app, including components and XHR callbacks, or even at scheduled intervals.
  • 39. DATA FLOW - 4 STEPS OF REDUX 2. The Redux store calls the reducer function you gave it. The store will pass two arguments to the reducer: the current state tree and the action. For example, in the todo app, the root reducer might receive something like this:
  • 40. let previousState = { visibleTodoFilter: 'SHOW_ALL', todos: [ { text: 'Read the docs.', complete: false } ] }
  • 41. // The action being performed (adding a todo) let action = { type: 'ADD_TODO', text: 'Understand the flow.' }
  • 42. // Your reducer returns the next application state let nextState = todoApp(previousState, action)
  • 43. DATA FLOW - 4 STEPS OF REDUX 3. The root reducer may combine the output of multiple reducers into a single state tree. REMEMBER How you structure the root reducer is completely up to you. Redux ships with a combineReducers() helper function, useful for “splitting” the root reducer into separate functions that each manage one branch of the state tree.
  • 44. function todos(state = [], action) { // Somehow calculate it... return nextState } function visibleTodoFilter(state = 'SHOW_ALL', action) { // Somehow calculate it... return nextState } let todoApp = combineReducers({ todos, visibleTodoFilter })
  • 45. When you emit an action, todoApp returned by combineReducers will call both reducers: let nextTodos = todos(state.todos, action) let nextVisibleTodoFilter = visibleTodoFilter(state.visibleTodoFilter, action) It will then combine both sets of results into a single state tree: return { todos: nextTodos, visibleTodoFilter: nextVisibleTodoFilter } While combineReducers() is a handy helper utility, you don't have to use it; feel free to write your own root reducer!
  • 46. DATA FLOW - 4 STEPS OF REDUX 4. The Redux store saves the complete state tree returned by the root reducer. This new tree is now the next state of your app! Every listener registered with store.subscribe(listener) will now be invoked; listeners may call store.getState() to get the current state. Now, the UI can be updated to reflect the new state. If you use bindings like React Redux, this is the point at which component.setState(newState) is called.