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!) // use default values, make sure you copy arrays and dont modify them. // reducers job is to take in an action and some data, then return a modified copy of the data based // on the action that was passed in const claimsHistory = (oldListOfClaims = [], action) => { if (action.type === 'CREATE_CLAIM') { //we care about this action (form) //never modify EXISTING data structure in reducers, create a copy and add the new data. return [...oldListOfClaims, action.payload]; //add a the claim to a NEW COPY of the oldlistofclaims } //we don't care about the form action.. 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; } //STORE const {createStore, combineReducers} = Redux; const ourDepartments = combineReducers({ accounting: accounting, claimsHistory: claimsHistory, policies: policies }); const store = createStore(ourDepartments); console.log(store.getState()); // accounting 100, policies 0 const action = createPolicy('Alex', 20); //take the action and send it to ALL reducers! store.dispatch(action); console.log(store.getState()); // accounting 120, policies 1 //can also be written like this store.dispatch(createPolicy('Jim', 20)); store.dispatch(createPolicy('Bob', 20)); store.dispatch(createClaim('Alex', 20)); store.dispatch(createClaim('Jim', 20)); store.dispatch(deletePolicy('Bob', 20)); console.log(store.getState());
Redux sample code
November 5, 2020
Code, JavaScript, React, Redux