(state, action)
| 7 | const ProductsContext = React.createContext(); |
| 8 | |
| 9 | const rootReducer = (state, action) => { |
| 10 | switch (action.type) { |
| 11 | case 'UPDATE_PRODUCTS': |
| 12 | return { |
| 13 | isLoaded: true, |
| 14 | products: action.payload, |
| 15 | images: state.images ? state.images : [], |
| 16 | }; |
| 17 | case 'EDIT_PRODUCT': { |
| 18 | const index = action.payload.id; |
| 19 | return { |
| 20 | ...state, |
| 21 | isLoaded: true, |
| 22 | products: state.products.map((c) => { |
| 23 | if (c.id === index) { |
| 24 | return { ...c, ...action.payload }; |
| 25 | } |
| 26 | return c; |
| 27 | }), |
| 28 | }; |
| 29 | } |
| 30 | |
| 31 | case 'GET_IMAGES': |
| 32 | return { |
| 33 | ...state, |
| 34 | images: action.payload, |
| 35 | }; |
| 36 | |
| 37 | case 'CREATE_PRODUCT': |
| 38 | state.products.push(action.payload); |
| 39 | return { |
| 40 | ...state, |
| 41 | isLoaded: true, |
| 42 | products: state.products, |
| 43 | }; |
| 44 | |
| 45 | default: |
| 46 | return { |
| 47 | ...state, |
| 48 | }; |
| 49 | } |
| 50 | }; |
| 51 | |
| 52 | const ProductsProvider = ({ children }) => { |
| 53 | const [products, setProducts] = React.useReducer(rootReducer, { |
nothing calls this directly
no outgoing calls
no test coverage detected