Created
March 10, 2021 18:11
-
-
Save ComradeCat24/6b1d9f45ebf90ae7f66e5f5a56418ba2 to your computer and use it in GitHub Desktop.
A project to understand "redux" lib
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(); | |
// People dropping off a form (Action Creators) | |
const createPolicy = (name, amount) => { | |
return { // Action (a form in our analogy) | |
type: 'CREATE_POLICY', | |
payload: { | |
name: name, | |
amount: amount | |
} | |
}; | |
}; | |
const deletePolicy = (name) => { | |
return { | |
type: 'DELETE_POLICY', | |
payload: { | |
name: name | |
} | |
}; | |
}; | |
const createClaim = (name, amountOfMoneyToCollect) => { | |
return { | |
type: 'CREATE_CLAIM', | |
payload: { | |
name: name, | |
amountOfMoneyToCollect: amountOfMoneyToCollect | |
} | |
}; | |
}; | |
// Reducers (Departments!) | |
const claimsHistory = (oldListOfClaims = [], action) => { | |
if (action.type === 'CREATE_CLAIM') { | |
// we care about this action (FORM!) | |
return [...oldListOfClaims, action.payload]; | |
} | |
// we don't care the action (form!!) | |
return oldListOfClaims; | |
}; | |
const accounting = (bagOfMoney = 100, action) => { | |
if (action.type === 'CREATE_CLAIM') { | |
return bagOfMoney - action.payload.amountOfMoneyToCollect; | |
} else 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]; | |
} else 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('Jerin', 20)); | |
store.dispatch(createPolicy('Nishant', 30)); | |
store.dispatch(createPolicy('Dhiraj', 40)); | |
store.dispatch(createClaim('Jerin', 120)); | |
store.dispatch(createClaim('Nishant', 50)); | |
store.dispatch(deletePolicy('Dhiraj')); | |
console.log(store.getState()); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment