Bob Bijvoet
Front-end Chapter Lead
Building Blocks 1
A predictable state container for JavaScript apps.
The state of your whole application is stored in an object tree within a single store.
The only way to mutate the state is to emit an action, an object describing what happened.
Changes are made with pure functions
To specify how the state tree is transformed by actions, you write pure reducers.
Pure function
The place where all your application state lives
//State
{
items:[],
done:true
}
Tells store that something happened and that the store should update itself in response.
//Action
{
type:'SOME_ACTION',
payload:{}
}
//Example
{
type:'ADD_TO_CART',
payload:{
id:1,
price:42
}
}
Responsible for mutating the store state when actions are dispatched
reducer(state, action) {
switch (action.type) {
case 'SOME_ACTION':
//Update state
}
return state;
}
reducer(state, action) {
switch (action.type) {
case 'ADD_TO_CART':
cart.push(action.payload)
break;
}
return state;
}
Provides the ability to create functions that extend the library.
Component architecture
Component architecture
sprint:{
number: 0,
burnedPoints: 0,
done:false
};
stories:[{
id:'1'
points:1,
description:'',
done:false
}]
{
type: 'STORY_DONE',
payload: {
id: story.id,
points:story.points
}
};
{
type:'SPRINT_DONE'
};
function storyDone(story) {
return {
type: 'STORY_DONE',
payload: {
id: story.id,
points:story.points
}
};
}
case 'STORY_DONE':
var story = state.stories.find(function(story) {
return story.id === action.payload.id;
});
if (story) {
story.done = true;
}
state.sprint.burnedPoints += action.payload.points;
break;
case 'SPRINT_DONE':
state.sprint.done = true;
Promise middleware
//Use of promise middleware
//Dispatch action with promise inside the payload
{
type: 'FETCH_PRODUCTS',
payload: {
promise: fetch('example.com/products')
}
//Automagically results in action:
//FETCH_PRODUCTS_PENDING
//And results in either:
//FETCH_PRODUCTS_FULFILLED or FETCH_PRODUCTS_REJECTED
//Then handle the actions inside of the reducer
case 'FETCH_PRODUCTS_PENDING':
state.loading = true;
state.error = false;
case 'FETCH_PRODUCTS_FULFILLED':
state.loading = false;
state.products = action.payload.products;
case 'FETCH_PRODUCTS_REJECTED':
state.loading = false;
state.error = true;
Switch to ing-assignment branch
https://github.com/bobbijvoet/ng-redux-session