Last active
November 5, 2019 13:39
-
-
Save aneurysmjs/9459d08b94125de195cee5bb3161370f to your computer and use it in GitHub Desktop.
redux stuff
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
// in this case the state is each individual product | |
const product = (state, action) => { | |
switch (action.type) { | |
case 'CREATE_PRODUCT': | |
return { | |
id: action.id, | |
name: action.name, | |
price: action.price, | |
}; | |
case 'EDIT_PRODUCT': | |
if (state.id !== action.id) { | |
return state; | |
} | |
return { | |
...state, | |
price: action.price, | |
}; | |
default: | |
return state; | |
} | |
}; | |
const products = (state = [], action) => { | |
switch (action.type) { | |
case 'CREATE_PRODUCT': | |
// delegate a reducer to handle each part of the state, is called | |
// "reducer composition" | |
return [...state, product(undefined, action)]; | |
case 'EDIT_PRODUCT': | |
return state.map(t => product(t, action)); | |
default: | |
return state; | |
} | |
}; | |
const cart = (state = {}, action) => { | |
switch (action.type) { | |
case 'ADD_TO_CART': | |
return { | |
quantity: state.products.length, | |
products: [...state.products, state.product], | |
}; | |
default: | |
return state; | |
} | |
}; | |
// this is pretty the same result using as combineReducers | |
// const appStore = (state = {}, action) => { | |
// return { | |
// cart: cart(state.products, action), | |
// products: products(state.products, action), | |
// }; | |
// }; | |
// "combinedReducers" returns the top-level reducer. | |
// The keys of the object given to "combinedReducers" will correspond | |
// to the fields that the state object is going to manage. | |
// The values of the object, are the reducers it should call to update the correspondence state fields. | |
const state = combineReducers({ | |
cart, | |
products, | |
}); | |
const store = createStore(state); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment