Skip to content

Instantly share code, notes, and snippets.

@dikamilo
Created July 20, 2020 20:18
Show Gist options
  • Save dikamilo/9b71b2c23195e2ecddc9ba4aac92f7a3 to your computer and use it in GitHub Desktop.
Save dikamilo/9b71b2c23195e2ecddc9ba4aac92f7a3 to your computer and use it in GitHub Desktop.
Introdution to redux
import Redux from 'redux';
console.clear();
// Action creators
const createPolicy = (name, amount) => {
return {
type: 'CREATE_POLICY',
payload: {
name, amount
}
};
};
const deletePolicy = name => {
return {
type: 'DELETE_POLICY',
payload: {
name
}
};
};
const createClaim = (name, amountOfMoneyToCollect) => {
return {
type: 'CREATE_CLAIM',
payload: {
name, amountOfMoneyToCollect
}
}
};
// Reducers
const claimsHistory = (oldListOfClaims = [], action) => {
if (action.type === 'CREATE_CLAIM') {
return [...oldListOfClaims, action.payload];
}
return oldListOfClaims;
};
const accounting = (bagOfMoney = 100, action) => {
if (action.type === 'CREATE_CLAIM') {
return bagOfMoney - action.payload.amountOfMoneyToCollect;
}
if (action.type === 'CREATE_POLICY') {
return bagOfMoney + action.payload.amount;
}
return bagOfMoney;
};
const policies = (listOfPolicies = [], action) => {
if (action.type === 'CREATE_POLICY') {
return [...listOfPolicies, action.payload.name];
}
if (action.type === 'DELETE_POLICY') {
return listOfPolicies.filter(name => name !== action.payload.name);
}
return listOfPolicies;
};
const {createStore, combineReducers} = Redux;
const ourDepartments = combineReducers({
accounting: accounting,
claimsHistory: claimsHistory,
policies: policies
});
const store = createStore(ourDepartments);
store.dispatch(createPolicy('Alex', 20));
store.dispatch(createPolicy('Jim', 30));
store.dispatch(createPolicy('Bob', 40));
store.dispatch(createClaim('Alex', 120));
store.dispatch(createClaim('Jim', 50));
store.dispatch(deletePolicy('Bob'));
console.log(store.getState());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment