Skip to content

Instantly share code, notes, and snippets.

@aneurysmjs
Last active November 5, 2019 13:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aneurysmjs/9459d08b94125de195cee5bb3161370f to your computer and use it in GitHub Desktop.
Save aneurysmjs/9459d08b94125de195cee5bb3161370f to your computer and use it in GitHub Desktop.
redux stuff
// 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