A Pen by Anshu Jalan on CodePen.
Last active
October 13, 2020 10:29
-
-
Save AnshuJalan/d791b21e755092c66ca8dc27394c112d to your computer and use it in GitHub Desktop.
Redux Scratch
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
console.clear(); | |
//[ACTION CREATOR] | |
const createPolicy = (name, amount) => { | |
//[ACTION] | |
return { | |
type: 'CREATE_POLICY', | |
payload: { | |
name, | |
amount | |
} | |
} | |
} | |
const claimPolicy = (name, amount) => { | |
return { | |
type: 'CLAIM_POLICY', | |
payload: { | |
name, | |
amount | |
} | |
} | |
} | |
const deletePolicy = (name) => { | |
return { | |
type: 'DELETE_POLICY', | |
payload: { | |
name | |
} | |
} | |
} | |
//[DISPATCHER] - provided by default in redux | |
//[REDUCERS] => Departments | |
const claimsHistory = (oldListOfClaims = [], action) => { | |
if(action.type === 'CLAIM_POLICY'){ | |
return [...oldListOfClaims, action]; | |
} | |
return oldListOfClaims; | |
} | |
const accounting = (bagOfMoney = 100, action) => { | |
if(action.type === 'CREATE_POLICY'){ | |
return bagOfMoney + action.payload.amount; | |
}else if(action.type === 'CLAIM_POLICY'){ | |
return bagOfMoney - action.payload.amount; | |
} | |
return bagOfMoney; | |
} | |
const policies = (listOfPolicies = [], action) => { | |
if(action.type === 'CREATE_POLICY'){ | |
return [...listOfPolicies, action.payload.name]; | |
}else if(action.type === 'DELETE_POLICY'){ | |
return listOfPolicies.filter( name => name !== action.payload.name ); | |
} | |
return listOfPolicies; | |
} | |
//REDUX | |
const { createStore, combineReducers } = Redux; | |
const ourDepartments = combineReducers({ | |
claimsHistory, | |
accounting, | |
policies | |
}); | |
const store = createStore(ourDepartments); | |
// We pass an action (FORM) to the dispatcher (FORM RECEIVER) which will transfer the form over onto all the reducers (DEPARTMENTS) | |
const action = createPolicy("Anshu", 50); | |
store.dispatch(action); | |
store.dispatch(createPolicy("Sushmita", 50)); | |
store.dispatch(createPolicy("Ronak", 40)); | |
store.dispatch(claimPolicy('Anshu', 20)); | |
console.log(store.getState()); | |
store.dispatch(deletePolicy('Ronak')) | |
console.log(store.getState()); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<script src="https://cdnjs.cloudflare.com/ajax/libs/redux/4.0.5/redux.min.js"></script> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment