SlideShare une entreprise Scribd logo
1  sur  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….

Contenu connexe

Tendances

Tendances (20)

Intro to React
Intro to ReactIntro to React
Intro to React
 
React.js and Redux overview
React.js and Redux overviewReact.js and Redux overview
React.js and Redux overview
 
React state management with Redux and MobX
React state management with Redux and MobXReact state management with Redux and MobX
React state management with Redux and MobX
 
React and redux
React and reduxReact and redux
React and redux
 
Introduction to React
Introduction to ReactIntroduction to React
Introduction to React
 
react redux.pdf
react redux.pdfreact redux.pdf
react redux.pdf
 
React JS: A Secret Preview
React JS: A Secret PreviewReact JS: A Secret Preview
React JS: A Secret Preview
 
Tech Talk on ReactJS
Tech Talk on ReactJSTech Talk on ReactJS
Tech Talk on ReactJS
 
The virtual DOM and how react uses it internally
The virtual DOM and how react uses it internallyThe virtual DOM and how react uses it internally
The virtual DOM and how react uses it internally
 
reactJS
reactJSreactJS
reactJS
 
Its time to React.js
Its time to React.jsIts time to React.js
Its time to React.js
 
React js
React jsReact js
React js
 
Intro to React
Intro to ReactIntro to React
Intro to React
 
React js programming concept
React js programming conceptReact js programming concept
React js programming concept
 
React hooks
React hooksReact hooks
React hooks
 
ReactJS
ReactJSReactJS
ReactJS
 
React state managmenet with Redux
React state managmenet with ReduxReact state managmenet with Redux
React state managmenet with Redux
 
React JS - Introduction
React JS - IntroductionReact JS - Introduction
React JS - Introduction
 
React Router: React Meetup XXL
React Router: React Meetup XXLReact Router: React Meetup XXL
React Router: React Meetup XXL
 
Introduction to react
Introduction to reactIntroduction to react
Introduction to react
 

Similaire à Redux Fundamentals: Actions, Reducers, Stores

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
 

Similaire à Redux Fundamentals: Actions, Reducers, Stores (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
 
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
 
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
 

Dernier

The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...
The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...
The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...ranjana rawat
 
Call Girls in Nagpur Suman Call 7001035870 Meet With Nagpur Escorts
Call Girls in Nagpur Suman Call 7001035870 Meet With Nagpur EscortsCall Girls in Nagpur Suman Call 7001035870 Meet With Nagpur Escorts
Call Girls in Nagpur Suman Call 7001035870 Meet With Nagpur EscortsCall Girls in Nagpur High Profile
 
Russian Call Girls in Nagpur Grishma Call 7001035870 Meet With Nagpur Escorts
Russian Call Girls in Nagpur Grishma Call 7001035870 Meet With Nagpur EscortsRussian Call Girls in Nagpur Grishma Call 7001035870 Meet With Nagpur Escorts
Russian Call Girls in Nagpur Grishma Call 7001035870 Meet With Nagpur EscortsCall Girls in Nagpur High Profile
 
CCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete Record
CCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete RecordCCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete Record
CCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete RecordAsst.prof M.Gokilavani
 
Processing & Properties of Floor and Wall Tiles.pptx
Processing & Properties of Floor and Wall Tiles.pptxProcessing & Properties of Floor and Wall Tiles.pptx
Processing & Properties of Floor and Wall Tiles.pptxpranjaldaimarysona
 
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...Dr.Costas Sachpazis
 
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 BookingVIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Bookingdharasingh5698
 
College Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
College Call Girls Nashik Nehal 7001305949 Independent Escort Service NashikCollege Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
College Call Girls Nashik Nehal 7001305949 Independent Escort Service NashikCall Girls in Nagpur High Profile
 
Booking open Available Pune Call Girls Pargaon 6297143586 Call Hot Indian Gi...
Booking open Available Pune Call Girls Pargaon  6297143586 Call Hot Indian Gi...Booking open Available Pune Call Girls Pargaon  6297143586 Call Hot Indian Gi...
Booking open Available Pune Call Girls Pargaon 6297143586 Call Hot Indian Gi...Call Girls in Nagpur High Profile
 
Extrusion Processes and Their Limitations
Extrusion Processes and Their LimitationsExtrusion Processes and Their Limitations
Extrusion Processes and Their Limitations120cr0395
 
Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...
Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...
Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...Christo Ananth
 
ONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdf
ONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdfONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdf
ONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdfKamal Acharya
 
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...ranjana rawat
 
Java Programming :Event Handling(Types of Events)
Java Programming :Event Handling(Types of Events)Java Programming :Event Handling(Types of Events)
Java Programming :Event Handling(Types of Events)simmis5
 
UNIT-III FMM. DIMENSIONAL ANALYSIS
UNIT-III FMM.        DIMENSIONAL ANALYSISUNIT-III FMM.        DIMENSIONAL ANALYSIS
UNIT-III FMM. DIMENSIONAL ANALYSISrknatarajan
 
(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...
(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...
(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...ranjana rawat
 
Glass Ceramics: Processing and Properties
Glass Ceramics: Processing and PropertiesGlass Ceramics: Processing and Properties
Glass Ceramics: Processing and PropertiesPrabhanshu Chaturvedi
 
Porous Ceramics seminar and technical writing
Porous Ceramics seminar and technical writingPorous Ceramics seminar and technical writing
Porous Ceramics seminar and technical writingrakeshbaidya232001
 

Dernier (20)

The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...
The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...
The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...
 
Call Girls in Nagpur Suman Call 7001035870 Meet With Nagpur Escorts
Call Girls in Nagpur Suman Call 7001035870 Meet With Nagpur EscortsCall Girls in Nagpur Suman Call 7001035870 Meet With Nagpur Escorts
Call Girls in Nagpur Suman Call 7001035870 Meet With Nagpur Escorts
 
Russian Call Girls in Nagpur Grishma Call 7001035870 Meet With Nagpur Escorts
Russian Call Girls in Nagpur Grishma Call 7001035870 Meet With Nagpur EscortsRussian Call Girls in Nagpur Grishma Call 7001035870 Meet With Nagpur Escorts
Russian Call Girls in Nagpur Grishma Call 7001035870 Meet With Nagpur Escorts
 
CCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete Record
CCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete RecordCCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete Record
CCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete Record
 
Processing & Properties of Floor and Wall Tiles.pptx
Processing & Properties of Floor and Wall Tiles.pptxProcessing & Properties of Floor and Wall Tiles.pptx
Processing & Properties of Floor and Wall Tiles.pptx
 
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
 
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 BookingVIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
 
College Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
College Call Girls Nashik Nehal 7001305949 Independent Escort Service NashikCollege Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
College Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
 
Water Industry Process Automation & Control Monthly - April 2024
Water Industry Process Automation & Control Monthly - April 2024Water Industry Process Automation & Control Monthly - April 2024
Water Industry Process Automation & Control Monthly - April 2024
 
Booking open Available Pune Call Girls Pargaon 6297143586 Call Hot Indian Gi...
Booking open Available Pune Call Girls Pargaon  6297143586 Call Hot Indian Gi...Booking open Available Pune Call Girls Pargaon  6297143586 Call Hot Indian Gi...
Booking open Available Pune Call Girls Pargaon 6297143586 Call Hot Indian Gi...
 
(INDIRA) Call Girl Aurangabad Call Now 8617697112 Aurangabad Escorts 24x7
(INDIRA) Call Girl Aurangabad Call Now 8617697112 Aurangabad Escorts 24x7(INDIRA) Call Girl Aurangabad Call Now 8617697112 Aurangabad Escorts 24x7
(INDIRA) Call Girl Aurangabad Call Now 8617697112 Aurangabad Escorts 24x7
 
Extrusion Processes and Their Limitations
Extrusion Processes and Their LimitationsExtrusion Processes and Their Limitations
Extrusion Processes and Their Limitations
 
Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...
Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...
Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...
 
ONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdf
ONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdfONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdf
ONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdf
 
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
 
Java Programming :Event Handling(Types of Events)
Java Programming :Event Handling(Types of Events)Java Programming :Event Handling(Types of Events)
Java Programming :Event Handling(Types of Events)
 
UNIT-III FMM. DIMENSIONAL ANALYSIS
UNIT-III FMM.        DIMENSIONAL ANALYSISUNIT-III FMM.        DIMENSIONAL ANALYSIS
UNIT-III FMM. DIMENSIONAL ANALYSIS
 
(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...
(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...
(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...
 
Glass Ceramics: Processing and Properties
Glass Ceramics: Processing and PropertiesGlass Ceramics: Processing and Properties
Glass Ceramics: Processing and Properties
 
Porous Ceramics seminar and technical writing
Porous Ceramics seminar and technical writingPorous Ceramics seminar and technical writing
Porous Ceramics seminar and technical writing
 

Redux Fundamentals: Actions, Reducers, Stores

  • 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.