Last active
May 29, 2017 05:27
-
-
Save emilong/876c30e936c0925b6eceee1a6cc81f5c to your computer and use it in GitHub Desktop.
Redux duck for makeup app
This file contains hidden or 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
const START_BRAND_FETCH = "makeup/api/START_BRAND_FETCH"; | |
const STORE_BRAND_PRODUCTS = "makeup/api/STORE_BRAND_PRODUCTS"; | |
const EMPTY_STATE = { brandsBeingFetched: [], brandProducts: {} }; | |
// Generally you may want to set this when running createStore(), but | |
// this may work too, depending on your redux state tree. See | |
// http://redux.js.org/docs/recipes/reducers/InitializingState.html | |
// for details. | |
const INITIAL_STATE = window.__PRELOADED_STATE__ || EMPTY_STATE; | |
// Reducer | |
export default function reducer(state = INITIAL_STATE, action = {}) { | |
const { type, brand, products } = action; | |
const { brandsBeingFetched = [], brandProducts = {} } = state; | |
switch (type) { | |
case START_BRAND_FETCH: | |
return Object.assign({}, state, { | |
brandsBeingFetched: brandsBeingFetched.concat([brand]) | |
}); | |
case STORE_BRAND_PRODUCTS: | |
return Object.assign({}, state, { | |
brandsBeingFetched: brandsBeingFetched.filter(b => b !== brand), | |
brandProducts: Object.assign({}, brandProducts, { [brand]: products }) | |
}); | |
default: | |
return state; | |
} | |
} | |
export function startBrandFetch(brand) { | |
return { type: START_BRAND_FETCH, brand }; | |
} | |
export function storeBrandProducts(brand, products) { | |
return { type: STORE_BRAND_PRODUCTS, brand, products }; | |
} | |
const brandUrl = brand => | |
`https://makeup-api.herokuapp.com/api/v1/products.json?brand=${brand.toLowerCase()}`; | |
export function fetchBrand(brand) { | |
return dispatch => { | |
dispatch(startBrandFetch(brand)); | |
fetch(brandUrl(brand)) | |
.then(response => response.json()) | |
.then(products => dispatch(storeBrandProducts(brand, products))); | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment