SlideShare ist ein Scribd-Unternehmen logo
1 von 47
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….

Weitere ähnliche Inhalte

Was ist angesagt?

Introduction to ReactJS
Introduction to ReactJSIntroduction to ReactJS
Introduction to ReactJSKnoldus Inc.
 
Getting Started with NgRx (Redux) Angular
Getting Started with NgRx (Redux) AngularGetting Started with NgRx (Redux) Angular
Getting Started with NgRx (Redux) AngularGustavo Costa
 
React + Redux + TypeScript === ♥
React + Redux + TypeScript === ♥React + Redux + TypeScript === ♥
React + Redux + TypeScript === ♥Remo Jansen
 
Introduction to react and redux
Introduction to react and reduxIntroduction to react and redux
Introduction to react and reduxCuong Ho
 
React new features and intro to Hooks
React new features and intro to HooksReact new features and intro to Hooks
React new features and intro to HooksSoluto
 
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 ITnamespaceit
 
React for Dummies
React for DummiesReact for Dummies
React for DummiesMitch Chen
 
React state managmenet with Redux
React state managmenet with ReduxReact state managmenet with Redux
React state managmenet with ReduxVedran Blaženka
 

Was ist angesagt? (20)

React js
React jsReact js
React js
 
React js
React jsReact js
React js
 
React and redux
React and reduxReact and redux
React and redux
 
react redux.pdf
react redux.pdfreact redux.pdf
react redux.pdf
 
Introduction to ReactJS
Introduction to ReactJSIntroduction to ReactJS
Introduction to ReactJS
 
React lecture
React lectureReact lecture
React lecture
 
reactJS
reactJSreactJS
reactJS
 
Getting Started with NgRx (Redux) Angular
Getting Started with NgRx (Redux) AngularGetting Started with NgRx (Redux) Angular
Getting Started with NgRx (Redux) Angular
 
React with Redux
React with ReduxReact with Redux
React with Redux
 
An Introduction to Redux
An Introduction to ReduxAn Introduction to Redux
An Introduction to Redux
 
React + Redux + TypeScript === ♥
React + Redux + TypeScript === ♥React + Redux + TypeScript === ♥
React + Redux + TypeScript === ♥
 
Introduction to react and redux
Introduction to react and reduxIntroduction to react and redux
Introduction to react and redux
 
Ngrx: Redux in angular
Ngrx: Redux in angularNgrx: Redux in angular
Ngrx: Redux in angular
 
React new features and intro to Hooks
React new features and intro to HooksReact new features and intro to Hooks
React new features and intro to Hooks
 
React JS - Introduction
React JS - IntroductionReact JS - Introduction
React JS - Introduction
 
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
 
Intro to React
Intro to ReactIntro to React
Intro to React
 
ReactJs
ReactJsReactJs
ReactJs
 
React for Dummies
React for DummiesReact for Dummies
React for Dummies
 
React state managmenet with Redux
React state managmenet with ReduxReact state managmenet with Redux
React state managmenet with Redux
 

Ähnlich wie Redux training

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 applicationKaty 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 appNitish Kumar
 
The evolution of redux action creators
The evolution of redux action creatorsThe evolution of redux action creators
The evolution of redux action creatorsGeorge 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 & ReduxVisual Engineering
 
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 2016Nir Kaufman
 
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 ReduxCommit University
 
React + Redux. Best practices
React + Redux.  Best practicesReact + Redux.  Best practices
React + Redux. Best practicesClickky
 
Introducing Vuex in your project
Introducing Vuex in your projectIntroducing Vuex in your project
Introducing Vuex in your projectDenny Biasiolli
 
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 VuexCommit University
 

Ähnlich wie Redux training (20)

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
 
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
 
Introducing Vuex in your project
Introducing Vuex in your projectIntroducing Vuex in your project
Introducing Vuex in your project
 
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
 
Vuex
VuexVuex
Vuex
 

Kürzlich hochgeladen

data_management_and _data_science_cheat_sheet.pdf
data_management_and _data_science_cheat_sheet.pdfdata_management_and _data_science_cheat_sheet.pdf
data_management_and _data_science_cheat_sheet.pdfJiananWang21
 
Online food ordering system project report.pdf
Online food ordering system project report.pdfOnline food ordering system project report.pdf
Online food ordering system project report.pdfKamal Acharya
 
Hazard Identification (HAZID) vs. Hazard and Operability (HAZOP): A Comparati...
Hazard Identification (HAZID) vs. Hazard and Operability (HAZOP): A Comparati...Hazard Identification (HAZID) vs. Hazard and Operability (HAZOP): A Comparati...
Hazard Identification (HAZID) vs. Hazard and Operability (HAZOP): A Comparati...soginsider
 
HOA1&2 - Module 3 - PREHISTORCI ARCHITECTURE OF KERALA.pptx
HOA1&2 - Module 3 - PREHISTORCI ARCHITECTURE OF KERALA.pptxHOA1&2 - Module 3 - PREHISTORCI ARCHITECTURE OF KERALA.pptx
HOA1&2 - Module 3 - PREHISTORCI ARCHITECTURE OF KERALA.pptxSCMS School of Architecture
 
Air Compressor reciprocating single stage
Air Compressor reciprocating single stageAir Compressor reciprocating single stage
Air Compressor reciprocating single stageAbc194748
 
Unleashing the Power of the SORA AI lastest leap
Unleashing the Power of the SORA AI lastest leapUnleashing the Power of the SORA AI lastest leap
Unleashing the Power of the SORA AI lastest leapRishantSharmaFr
 
Generative AI or GenAI technology based PPT
Generative AI or GenAI technology based PPTGenerative AI or GenAI technology based PPT
Generative AI or GenAI technology based PPTbhaskargani46
 
Bridge Jacking Design Sample Calculation.pptx
Bridge Jacking Design Sample Calculation.pptxBridge Jacking Design Sample Calculation.pptx
Bridge Jacking Design Sample Calculation.pptxnuruddin69
 
COST-EFFETIVE and Energy Efficient BUILDINGS ptx
COST-EFFETIVE  and Energy Efficient BUILDINGS ptxCOST-EFFETIVE  and Energy Efficient BUILDINGS ptx
COST-EFFETIVE and Energy Efficient BUILDINGS ptxJIT KUMAR GUPTA
 
Work-Permit-Receiver-in-Saudi-Aramco.pptx
Work-Permit-Receiver-in-Saudi-Aramco.pptxWork-Permit-Receiver-in-Saudi-Aramco.pptx
Work-Permit-Receiver-in-Saudi-Aramco.pptxJuliansyahHarahap1
 
DeepFakes presentation : brief idea of DeepFakes
DeepFakes presentation : brief idea of DeepFakesDeepFakes presentation : brief idea of DeepFakes
DeepFakes presentation : brief idea of DeepFakesMayuraD1
 
DC MACHINE-Motoring and generation, Armature circuit equation
DC MACHINE-Motoring and generation, Armature circuit equationDC MACHINE-Motoring and generation, Armature circuit equation
DC MACHINE-Motoring and generation, Armature circuit equationBhangaleSonal
 
kiln thermal load.pptx kiln tgermal load
kiln thermal load.pptx kiln tgermal loadkiln thermal load.pptx kiln tgermal load
kiln thermal load.pptx kiln tgermal loadhamedmustafa094
 
+97470301568>> buy weed in qatar,buy thc oil qatar,buy weed and vape oil in d...
+97470301568>> buy weed in qatar,buy thc oil qatar,buy weed and vape oil in d...+97470301568>> buy weed in qatar,buy thc oil qatar,buy weed and vape oil in d...
+97470301568>> buy weed in qatar,buy thc oil qatar,buy weed and vape oil in d...Health
 
Hostel management system project report..pdf
Hostel management system project report..pdfHostel management system project report..pdf
Hostel management system project report..pdfKamal Acharya
 
Online electricity billing project report..pdf
Online electricity billing project report..pdfOnline electricity billing project report..pdf
Online electricity billing project report..pdfKamal Acharya
 
Computer Networks Basics of Network Devices
Computer Networks  Basics of Network DevicesComputer Networks  Basics of Network Devices
Computer Networks Basics of Network DevicesChandrakantDivate1
 

Kürzlich hochgeladen (20)

data_management_and _data_science_cheat_sheet.pdf
data_management_and _data_science_cheat_sheet.pdfdata_management_and _data_science_cheat_sheet.pdf
data_management_and _data_science_cheat_sheet.pdf
 
Online food ordering system project report.pdf
Online food ordering system project report.pdfOnline food ordering system project report.pdf
Online food ordering system project report.pdf
 
Hazard Identification (HAZID) vs. Hazard and Operability (HAZOP): A Comparati...
Hazard Identification (HAZID) vs. Hazard and Operability (HAZOP): A Comparati...Hazard Identification (HAZID) vs. Hazard and Operability (HAZOP): A Comparati...
Hazard Identification (HAZID) vs. Hazard and Operability (HAZOP): A Comparati...
 
Cara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak Hamil
Cara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak HamilCara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak Hamil
Cara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak Hamil
 
HOA1&2 - Module 3 - PREHISTORCI ARCHITECTURE OF KERALA.pptx
HOA1&2 - Module 3 - PREHISTORCI ARCHITECTURE OF KERALA.pptxHOA1&2 - Module 3 - PREHISTORCI ARCHITECTURE OF KERALA.pptx
HOA1&2 - Module 3 - PREHISTORCI ARCHITECTURE OF KERALA.pptx
 
Air Compressor reciprocating single stage
Air Compressor reciprocating single stageAir Compressor reciprocating single stage
Air Compressor reciprocating single stage
 
Unleashing the Power of the SORA AI lastest leap
Unleashing the Power of the SORA AI lastest leapUnleashing the Power of the SORA AI lastest leap
Unleashing the Power of the SORA AI lastest leap
 
Generative AI or GenAI technology based PPT
Generative AI or GenAI technology based PPTGenerative AI or GenAI technology based PPT
Generative AI or GenAI technology based PPT
 
Bridge Jacking Design Sample Calculation.pptx
Bridge Jacking Design Sample Calculation.pptxBridge Jacking Design Sample Calculation.pptx
Bridge Jacking Design Sample Calculation.pptx
 
COST-EFFETIVE and Energy Efficient BUILDINGS ptx
COST-EFFETIVE  and Energy Efficient BUILDINGS ptxCOST-EFFETIVE  and Energy Efficient BUILDINGS ptx
COST-EFFETIVE and Energy Efficient BUILDINGS ptx
 
Work-Permit-Receiver-in-Saudi-Aramco.pptx
Work-Permit-Receiver-in-Saudi-Aramco.pptxWork-Permit-Receiver-in-Saudi-Aramco.pptx
Work-Permit-Receiver-in-Saudi-Aramco.pptx
 
DeepFakes presentation : brief idea of DeepFakes
DeepFakes presentation : brief idea of DeepFakesDeepFakes presentation : brief idea of DeepFakes
DeepFakes presentation : brief idea of DeepFakes
 
DC MACHINE-Motoring and generation, Armature circuit equation
DC MACHINE-Motoring and generation, Armature circuit equationDC MACHINE-Motoring and generation, Armature circuit equation
DC MACHINE-Motoring and generation, Armature circuit equation
 
kiln thermal load.pptx kiln tgermal load
kiln thermal load.pptx kiln tgermal loadkiln thermal load.pptx kiln tgermal load
kiln thermal load.pptx kiln tgermal load
 
+97470301568>> buy weed in qatar,buy thc oil qatar,buy weed and vape oil in d...
+97470301568>> buy weed in qatar,buy thc oil qatar,buy weed and vape oil in d...+97470301568>> buy weed in qatar,buy thc oil qatar,buy weed and vape oil in d...
+97470301568>> buy weed in qatar,buy thc oil qatar,buy weed and vape oil in d...
 
Integrated Test Rig For HTFE-25 - Neometrix
Integrated Test Rig For HTFE-25 - NeometrixIntegrated Test Rig For HTFE-25 - Neometrix
Integrated Test Rig For HTFE-25 - Neometrix
 
Hostel management system project report..pdf
Hostel management system project report..pdfHostel management system project report..pdf
Hostel management system project report..pdf
 
Online electricity billing project report..pdf
Online electricity billing project report..pdfOnline electricity billing project report..pdf
Online electricity billing project report..pdf
 
Call Girls in South Ex (delhi) call me [🔝9953056974🔝] escort service 24X7
Call Girls in South Ex (delhi) call me [🔝9953056974🔝] escort service 24X7Call Girls in South Ex (delhi) call me [🔝9953056974🔝] escort service 24X7
Call Girls in South Ex (delhi) call me [🔝9953056974🔝] escort service 24X7
 
Computer Networks Basics of Network Devices
Computer Networks  Basics of Network DevicesComputer Networks  Basics of Network Devices
Computer Networks Basics of Network Devices
 

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.