Skip to content

Instantly share code, notes, and snippets.

@median-man
Created September 29, 2019 14:29
Show Gist options
  • Save median-man/6910dd7fc81d57fed6a69e151dcde80b to your computer and use it in GitHub Desktop.
Save median-man/6910dd7fc81d57fed6a69e151dcde80b to your computer and use it in GitHub Desktop.
Basic Redux Example
/*
This is a copy/paste from codepen.io. (https://codepen.io/john-desrosiers/pen/vYBwjrG?editors=0010)
The revealing module pattern with IIFE is used since only a single js file is used for the pen.
*/
const { createStore, combineReducers } = Redux
const actionTypes = Object.freeze({
CREATE_POLICY: 'create insurance policy',
DELETE_POLICY: 'cancel insurance policy',
CREATE_CLAIM: 'make an insurance claim'
})
// start by making an "Action Creator" and an "Action"
// Actions: (people dropping off form for insurance company)
const actions = (() => {
const { CREATE_POLICY, DELETE_POLICY, CREATE_CLAIM } = actionTypes
const createPolicy = ({ name, amount }) => {
return {
type: CREATE_POLICY,
payload: { name, amount }
}
}
const deletePolicy = ({ name }) => {
return {
type: DELETE_POLICY,
payload: { name }
}
}
const createClaim = ({ name, amount }) => {
return {
type: CREATE_CLAIM,
payload: { name, amount }
}
}
return { createPolicy, deletePolicy, createClaim }
})()
// reducers: (departments that act on the form)
const reducers = (() => {
const claimsHistory = (oldListOfClaims = [], action) => {
if (action.type === actionTypes.CREATE_CLAIM) {
return [...oldListOfClaims, { ...action.payload }]
}
return oldListOfClaims
}
const accounting = (bagOfMoney = 0, action) => {
if (action.type === actionTypes.CREATE_CLAIM) {
return bagOfMoney - action.payload.amount
}
if (action.type === actionTypes.CREATE_POLICY) {
return bagOfMoney + action.payload.amount
}
return bagOfMoney
}
const policies = (listOfPolicies = [], action) => {
if (action.type === actionTypes.CREATE_POLICY) {
return [...listOfPolicies, { ...action.payload }]
}
if (action.type === actionTypes.DELETE_POLICY) {
return listOfPolicies.filter(policy => policy.name !== action.payload.name)
}
return listOfPolicies
}
return { claimsHistory, accounting, policies }
})()
const departmentsReducers = combineReducers(reducers)
const initialState = {
claimsHistory: [],
accounting: 100,
policies: []
}
const store = createStore(departmentsReducers, initialState)
store.dispatch(actions.createPolicy({ name: 'Alex', amount: 20 }))
store.dispatch(actions.createPolicy({ name: 'Jim', amount: 30 }))
store.dispatch(actions.createPolicy({ name: 'Bob', amount: 40 }))
store.dispatch(actions.createClaim({ name: 'Alex', amount: 120 }))
store.dispatch(actions.createClaim({ name: 'Jim', amount: 10 }))
store.dispatch(actions.deletePolicy({ name: 'Bob' }))
console.log(store.getState())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment