├── .gitignore ├── README.md ├── package.json ├── public ├── favicon.ico ├── index.html └── manifest.json ├── src ├── App.scss ├── App.test.tsx ├── App.tsx ├── actions │ ├── cart.ts │ └── constants.ts ├── components │ ├── CountView.tsx │ └── ProductItem.tsx ├── containers │ ├── CartContainerHooks.tsx │ ├── CartContainerOld.tsx │ ├── ParentContainer.tsx │ ├── ProductListContainer.tsx │ └── ProductListHooks.tsx ├── hooks │ ├── index.ts │ └── useDispatchToStore.ts ├── index.css ├── index.tsx ├── logo.svg ├── react-app-env.d.ts ├── reducers │ ├── cart.ts │ ├── cartOld.ts │ ├── index.ts │ ├── productOld.ts │ ├── products.ts │ └── storeHours.ts ├── serviceWorker.ts ├── store │ └── index.ts ├── styles │ ├── _styles.scss │ ├── components │ │ ├── _components.scss │ │ └── _productItem.scss │ └── containers │ │ └── _containers.scss └── types │ ├── cart.types.ts │ ├── index.ts │ ├── products.types.ts │ ├── store.types.ts │ └── storeHours.types.ts ├── tsconfig.json └── yarn.lock /.gitignore: -------------------------------------------------------------------------------- 1 | # See https://help.github.com/articles/ignoring-files/ for more about ignoring files. 2 | 3 | # dependencies 4 | /node_modules 5 | /.pnp 6 | .pnp.js 7 | 8 | # testing 9 | /coverage 10 | 11 | # production 12 | /build 13 | 14 | # misc 15 | .DS_Store 16 | .env.local 17 | .env.development.local 18 | .env.test.local 19 | .env.production.local 20 | 21 | npm-debug.log* 22 | yarn-debug.log* 23 | yarn-error.log* 24 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | Playing around with the new Redux hooks with typescript. 2 | 3 | The plan is to compare the perfomance of connect and traditional methods of connecting to the store vs the new useSelector hook. 4 | 5 | I am also really curious on the performance with these new hooks and how they will work in conjunction with useMemo and useCallback. 6 | 7 | Added Reselect but will need to do a usecase where we use a selector in multiple component instances. 8 | 9 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "shop-store-reselect", 3 | "version": "0.1.0", 4 | "private": true, 5 | "dependencies": { 6 | "@types/jest": "24.0.14", 7 | "@types/node": "12.0.8", 8 | "@types/ramda": "^0.26.9", 9 | "@types/react": "16.8.20", 10 | "@types/react-dom": "16.8.4", 11 | "@types/react-redux": "^7.1.0", 12 | "lodash": "^4.17.14", 13 | "node-sass": "^4.12.0", 14 | "ramda": "^0.26.1", 15 | "react": "^16.8.6", 16 | "react-dom": "^16.8.6", 17 | "react-redux": "^7.1.0", 18 | "react-scripts": "3.0.1", 19 | "redux": "^4.0.1", 20 | "redux-thunk": "^2.3.0", 21 | "reselect": "^4.0.0", 22 | "typescript": "3.5.2" 23 | }, 24 | "scripts": { 25 | "start": "react-scripts start", 26 | "build": "react-scripts build", 27 | "test": "react-scripts test", 28 | "eject": "react-scripts eject" 29 | }, 30 | "eslintConfig": { 31 | "extends": "react-app" 32 | }, 33 | "browserslist": { 34 | "production": [ 35 | ">0.2%", 36 | "not dead", 37 | "not op_mini all" 38 | ], 39 | "development": [ 40 | "last 1 chrome version", 41 | "last 1 firefox version", 42 | "last 1 safari version" 43 | ] 44 | }, 45 | "devDependencies": {} 46 | } 47 | -------------------------------------------------------------------------------- /public/favicon.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/terencejeong/redux-hooks-api-play/32eb8bbb233b6902c00d479930af7ba6f6b93350/public/favicon.ico -------------------------------------------------------------------------------- /public/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 12 | 13 | 22 | React App 23 | 24 | 25 | 26 |
27 | 37 | 38 | 39 | -------------------------------------------------------------------------------- /public/manifest.json: -------------------------------------------------------------------------------- 1 | { 2 | "short_name": "React App", 3 | "name": "Create React App Sample", 4 | "icons": [ 5 | { 6 | "src": "favicon.ico", 7 | "sizes": "64x64 32x32 24x24 16x16", 8 | "type": "image/x-icon" 9 | } 10 | ], 11 | "start_url": ".", 12 | "display": "standalone", 13 | "theme_color": "#000000", 14 | "background_color": "#ffffff" 15 | } 16 | -------------------------------------------------------------------------------- /src/App.scss: -------------------------------------------------------------------------------- 1 | @import './styles/_styles.scss'; -------------------------------------------------------------------------------- /src/App.test.tsx: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | import ReactDOM from 'react-dom'; 3 | import App from './App'; 4 | 5 | it('renders without crashing', () => { 6 | const div = document.createElement('div'); 7 | ReactDOM.render(, div); 8 | ReactDOM.unmountComponentAtNode(div); 9 | }); 10 | -------------------------------------------------------------------------------- /src/App.tsx: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | import './App.scss'; 3 | import ParentContainer from './containers/ParentContainer'; 4 | 5 | const App: React.FC = () => { 6 | return ( 7 |
8 | 9 |
10 | ); 11 | } 12 | 13 | export default App; 14 | -------------------------------------------------------------------------------- /src/actions/cart.ts: -------------------------------------------------------------------------------- 1 | import { Dispatch } from 'redux'; 2 | import { Product } from '../types' 3 | import { actions } from './constants'; 4 | 5 | const addToCartSafe: Function = (product: Product) => ({ 6 | type: actions.ADD_TO_CART, 7 | payload: product 8 | }); 9 | 10 | export const addToCart = (product: Product) => (dispatch: Dispatch, getState: Function) => { 11 | dispatch(addToCartSafe(product)); 12 | }; -------------------------------------------------------------------------------- /src/actions/constants.ts: -------------------------------------------------------------------------------- 1 | export const actions = { 2 | ADD_TO_CART: 'ADD_TO_CART', 3 | SET_PRODUCTS: 'SET_PRODUCTS', 4 | STORE_OPERATING: 'STORE_OPERATING', 5 | ADD_TO_CART_OLD:'ADD_TO_CART_OLD', 6 | SET_PRODUCTS_OLD: 'SET_PRODUCTS_OLD', 7 | } -------------------------------------------------------------------------------- /src/components/CountView.tsx: -------------------------------------------------------------------------------- 1 | import React, {memo} from 'react' 2 | 3 | const CountView = memo((props: any) => ( 4 |
5 | {props.count} 6 |
7 | )); 8 | 9 | export default CountView; -------------------------------------------------------------------------------- /src/components/ProductItem.tsx: -------------------------------------------------------------------------------- 1 | import React, { memo, MouseEvent } from 'react'; 2 | import { partial } from 'ramda'; 3 | import { Product } from '../types'; 4 | 5 | const ProductItem: Function = memo((({ product, dispatchToStore }: ProductItemProps) => { 6 | function handleClick(product: Product, event: MouseEvent, ) { 7 | event.preventDefault(); 8 | dispatchToStore(product); 9 | } 10 | return ( 11 |
12 |
13 | {product.title} 14 |
15 |
16 | ${product.value} 17 |
18 |
19 | x {product.quantity} 20 |
21 |
22 | 28 |
29 |
30 | ) 31 | } 32 | )) 33 | 34 | type ProductItemProps = { 35 | product: Product, 36 | dispatchToStore: Function 37 | } 38 | 39 | export default ProductItem; -------------------------------------------------------------------------------- /src/containers/CartContainerHooks.tsx: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | import { useSelector } from 'react-redux'; 3 | import { createSelector } from 'reselect'; 4 | import { AppStore, CartItem } from '../types'; 5 | 6 | type cartSelectorData = { 7 | shoppingCart: CartItem[], 8 | shoppingCartTotal: number 9 | } 10 | 11 | const getShoppingCart = (state: AppStore): CartItem[] => { 12 | return state.cartsModule.cart; 13 | } 14 | 15 | const makeShoppingCartSelector = createSelector( 16 | [getShoppingCart], 17 | (shoppingCart: CartItem[]): cartSelectorData => { 18 | const shoppingCartTotal = shoppingCart.reduce((accum: number, current: CartItem) => { 19 | return accum + (current.value * current.quantityBought) 20 | }, 0) 21 | return { 22 | shoppingCart, 23 | shoppingCartTotal 24 | } 25 | } 26 | ) 27 | 28 | const CartContainerHooks: React.FC = () => { 29 | // since we are using selectors here, these values are only recalculated when state.cartsModule.cart changes. 30 | const cartsModule: cartSelectorData = useSelector((state: AppStore) => makeShoppingCartSelector(state)); 31 | return ( 32 | <> 33 |

Cart Container with useSelector Hooks and Reselect

34 |
35 | { 36 | cartsModule.shoppingCart.map((item: CartItem) => { 37 | return ( 38 |
39 | {item.id} {item.quantityBought} 40 |
41 | ) 42 | }) 43 | } 44 | Total Price: ${cartsModule.shoppingCartTotal} 45 |
46 |
47 | 48 | ) 49 | }; 50 | 51 | export default CartContainerHooks; -------------------------------------------------------------------------------- /src/containers/CartContainerOld.tsx: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | import { connect } from 'react-redux'; 3 | import { AppStore, CartItem } from '../types'; 4 | 5 | function getCartPrice(cart: any) { 6 | return cart.reduce((accum: number, current: CartItem) => { 7 | return accum + (current.value * current.quantityBought) 8 | }, 0) 9 | } 10 | 11 | // TODO Fix all the types. 12 | const mapStateToProps = (state: AppStore) => ({ 13 | shoppingCart: state.cartsOldModule.cart, 14 | shoppingCartTotal: getCartPrice(state.cartsOldModule.cart) 15 | }); 16 | 17 | const CartContainerOld: React.FC = (props: any) => { 18 | return ( 19 | <> 20 |

Tried and true Cart Container with Connect

21 |
22 | { 23 | props.shoppingCart.map((item: CartItem) => { 24 | return ( 25 |
26 | {item.id} {item.quantityBought} 27 |
28 | ) 29 | }) 30 | } 31 | Total Price: ${props.shoppingCartTotal} 32 |
33 |
34 | 35 | ) 36 | } 37 | 38 | export default connect(mapStateToProps)(CartContainerOld); -------------------------------------------------------------------------------- /src/containers/ParentContainer.tsx: -------------------------------------------------------------------------------- 1 | import React, {useCallback} from 'react'; 2 | import { useSelector, useDispatch } from 'react-redux'; 3 | import { AppStore, StoreHours } from '../types'; 4 | import { actions } from '../actions/constants'; 5 | import ProductListHooks from './ProductListHooks'; 6 | import CartContainerHooks from './CartContainerHooks'; 7 | import CartContainerOld from './CartContainerOld'; 8 | import ProductListContainer from './ProductListContainer'; 9 | 10 | const ParentContainer: React.FC = () => { 11 | const storeHoursModule: StoreHours = useSelector((state: AppStore) => state.storeHoursModule); 12 | const handleStoreHours = useDispatch(); 13 | const handleStore = useCallback( 14 | () => handleStoreHours({type: actions.STORE_OPERATING}), 15 | [handleStoreHours] 16 | ) 17 | return ( 18 | <> 19 |
20 |

{storeHoursModule.open ? 'OPEN' : 'CLOSE'}

21 | 26 |
27 | 28 | 29 | 30 | 31 | 32 | ) 33 | }; 34 | 35 | export default ParentContainer; -------------------------------------------------------------------------------- /src/containers/ProductListContainer.tsx: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | import { Dispatch } from 'redux'; 3 | import { connect } from 'react-redux'; 4 | import ProductItem from '../components/ProductItem'; 5 | import { AppStore, Product } from '../types'; 6 | import { actions } from '../actions/constants'; 7 | 8 | // TODO Fix all the types. 9 | const mapStateToProps = (state: AppStore) => ({ 10 | products: state.productsOldModule.products 11 | }); 12 | 13 | const mapDispatchToProps = (dispatch: Dispatch) => { 14 | return { 15 | addItem: (product: Product) => dispatch({ type: actions.ADD_TO_CART_OLD, payload: product }) 16 | } 17 | } 18 | 19 | const ProductListContainer: React.FC = (props: any) => { 20 | const { products } = props; 21 | return ( 22 | <> 23 |

This is the tried and trusty connect

24 |
25 | { 26 | products.map((product: Product) => { 27 | return ( 28 | 29 | ) 30 | }) 31 | } 32 |
33 |
34 | 35 | ) 36 | }; 37 | 38 | export default connect(mapStateToProps, mapDispatchToProps)(ProductListContainer); 39 | -------------------------------------------------------------------------------- /src/containers/ProductListHooks.tsx: -------------------------------------------------------------------------------- 1 | import React, { useCallback, useState, memo } from 'react'; 2 | import { useSelector, shallowEqual } from 'react-redux'; 3 | import { AppStore, Product } from '../types'; 4 | import { useDispatchToStore } from '../hooks'; 5 | import ProductItem from '../components/ProductItem'; 6 | import CountView from '../components/CountView'; 7 | import { actions } from '../actions/constants'; 8 | 9 | const ProductListHooks: React.FC = memo(() => { 10 | 11 | const products: Product[] = useSelector((state: AppStore) => state.productsModule.products, shallowEqual); 12 | 13 | const handleDispatch = useDispatchToStore(actions.ADD_TO_CART); 14 | 15 | const dispatchToStore = useCallback( 16 | handleDispatch, 17 | [actions.ADD_TO_CART] 18 | ); 19 | 20 | const [count, setCount] = useState(0); 21 | 22 | return ( 23 | <> 24 |

Product Container with useSelector Hooks

25 | { 26 | products.map((product: Product) => { 27 | return ( 28 | 29 | ) 30 | }) 31 | } 32 |
33 | 34 | 35 | 36 | ) 37 | }); 38 | 39 | export default ProductListHooks; -------------------------------------------------------------------------------- /src/hooks/index.ts: -------------------------------------------------------------------------------- 1 | export { default as useDispatchToStore } from './useDispatchToStore' -------------------------------------------------------------------------------- /src/hooks/useDispatchToStore.ts: -------------------------------------------------------------------------------- 1 | import { Dispatch } from 'redux'; 2 | import { useDispatch } from 'react-redux'; 3 | 4 | // TODO: Fix the payload type. 5 | export default function useDispatchToStore(type: string) { 6 | const dispatch: Dispatch = useDispatch(); 7 | return (payload: any) => { 8 | dispatch({ type, payload }) 9 | } 10 | }; -------------------------------------------------------------------------------- /src/index.css: -------------------------------------------------------------------------------- 1 | body { 2 | margin: 0; 3 | font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen', 4 | 'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue', 5 | sans-serif; 6 | -webkit-font-smoothing: antialiased; 7 | -moz-osx-font-smoothing: grayscale; 8 | } 9 | 10 | code { 11 | font-family: source-code-pro, Menlo, Monaco, Consolas, 'Courier New', 12 | monospace; 13 | } 14 | -------------------------------------------------------------------------------- /src/index.tsx: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | import ReactDOM from 'react-dom'; 3 | import { Provider } from 'react-redux'; 4 | import store from './store'; 5 | import './index.css'; 6 | import App from './App'; 7 | import * as serviceWorker from './serviceWorker'; 8 | 9 | ReactDOM.render( 10 | 11 | 12 | , 13 | document.getElementById('root') 14 | ); 15 | 16 | // If you want your app to work offline and load faster, you can change 17 | // unregister() to register() below. Note this comes with some pitfalls. 18 | // Learn more about service workers: https://bit.ly/CRA-PWA 19 | serviceWorker.unregister(); 20 | -------------------------------------------------------------------------------- /src/logo.svg: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /src/react-app-env.d.ts: -------------------------------------------------------------------------------- 1 | /// 2 | -------------------------------------------------------------------------------- /src/reducers/cart.ts: -------------------------------------------------------------------------------- 1 | import { Action, Reducer } from 'redux'; 2 | import { Cart, CartItem, Product } from '../types'; 3 | import { actions } from '../actions/constants'; 4 | 5 | const initialState: Cart = { 6 | cart: [], 7 | isLoading: false, 8 | error: false 9 | }; 10 | 11 | const addItemToCart: Function = (cart: CartItem[], product: Product): CartItem[] => { 12 | 13 | const { quantity, ...item } = product; 14 | 15 | let foundItem = cart.find((item: CartItem) => item.id === product.id); 16 | 17 | if (foundItem) return cart.map((item: CartItem) => item.id === product.id ? { ...item, quantityBought: item.quantityBought + 1 } : item); 18 | 19 | return [ 20 | ...cart, 21 | { ...item, quantityBought: 1 } 22 | ] 23 | }; 24 | 25 | export const cart: Reducer = (state = initialState, action: any) => { 26 | 27 | switch (action.type) { 28 | case actions.ADD_TO_CART: 29 | return { 30 | ...state, 31 | cart: addItemToCart(state.cart, action.payload) 32 | } 33 | default: 34 | return { 35 | ...state 36 | } 37 | } 38 | } -------------------------------------------------------------------------------- /src/reducers/cartOld.ts: -------------------------------------------------------------------------------- 1 | import { Action, Reducer } from 'redux'; 2 | import { Cart, CartItem, Product } from '../types'; 3 | import { actions } from '../actions/constants'; 4 | 5 | const initialState: Cart = { 6 | cart: [], 7 | isLoading: false, 8 | error: false 9 | }; 10 | 11 | const addItemToCart: Function = (cart: CartItem[], product: Product): CartItem[] => { 12 | 13 | const { quantity, ...item } = product; 14 | 15 | let foundItem = cart.find((item: CartItem) => item.id === product.id); 16 | 17 | if (foundItem) return cart.map((item: CartItem) => item.id === product.id ? { ...item, quantityBought: item.quantityBought + 1 } : item) 18 | 19 | return [ 20 | ...cart, 21 | { ...item, quantityBought: 1 } 22 | ] 23 | } 24 | 25 | export const cartOld: Reducer = (state = initialState, action: any) => { 26 | 27 | switch (action.type) { 28 | case actions.ADD_TO_CART_OLD: 29 | return { 30 | ...state, 31 | cart: addItemToCart(state.cart, action.payload) 32 | } 33 | default: 34 | return { 35 | ...state 36 | } 37 | } 38 | } -------------------------------------------------------------------------------- /src/reducers/index.ts: -------------------------------------------------------------------------------- 1 | import { combineReducers } from 'redux'; 2 | import { cart } from './cart'; 3 | import { cartOld } from './cartOld'; 4 | import { products } from './products'; 5 | import { productsOld } from './productOld'; 6 | import { storeHours } from './storeHours'; 7 | 8 | const reducers = combineReducers({ 9 | cartsModule: cart, 10 | cartsOldModule: cartOld, 11 | productsModule: products, 12 | storeHoursModule: storeHours, 13 | productsOldModule: productsOld 14 | }); 15 | 16 | export default reducers; -------------------------------------------------------------------------------- /src/reducers/productOld.ts: -------------------------------------------------------------------------------- 1 | // need to import the actions 2 | import { Products, Product } from '../types'; 3 | import { actions } from '../actions/constants'; 4 | 5 | const initialState: Products = { 6 | products: [ 7 | { 8 | id: '3a', 9 | title: 'MacBook Old', 10 | value: 2000, 11 | quantity: 3 12 | }, 13 | { 14 | id: '4b', 15 | title: 'iPad Old', 16 | value: 1200, 17 | quantity: 6 18 | }, 19 | { 20 | id: '5c', 21 | title: 'iPod Classic Old', 22 | value: 400, 23 | quantity: 1 24 | }, 25 | ], 26 | loading: false, 27 | error: false 28 | }; 29 | 30 | const getProduct = (state: Products, selectedProduct: Product): Product[] => 31 | state.products.map((product: Product) => 32 | (product.id === selectedProduct.id ? { ...product, quantity: product.quantity - 1 } : product)); 33 | 34 | export const productsOld = (state = initialState, action: any) => { 35 | 36 | switch (action.type) { 37 | case actions.SET_PRODUCTS_OLD: 38 | return { 39 | ...state, 40 | } 41 | 42 | case actions.ADD_TO_CART_OLD: 43 | return { 44 | ...state, 45 | products: getProduct(state, action.payload) 46 | } 47 | default: 48 | return { 49 | ...state 50 | } 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /src/reducers/products.ts: -------------------------------------------------------------------------------- 1 | // need to import the actions 2 | import { Products, Product } from '../types'; 3 | import { actions } from '../actions/constants'; 4 | 5 | const initialState: Products = { 6 | products: [ 7 | { 8 | id: '1a', 9 | title: 'MacBook Pro', 10 | value: 2000, 11 | quantity: 3 12 | }, 13 | { 14 | id: '2b', 15 | title: 'iPad', 16 | value: 1200, 17 | quantity: 6 18 | }, 19 | { 20 | id: '3c', 21 | title: 'iPod Classic', 22 | value: 400, 23 | quantity: 1 24 | }, 25 | ], 26 | loading: false, 27 | error: false 28 | }; 29 | 30 | const getProduct = (state: Products, selectedProduct: Product): Product[] => 31 | state.products.map((product: Product) => 32 | (product.id === selectedProduct.id ? { ...product, quantity: product.quantity - 1 } : product)); 33 | 34 | export const products = (state = initialState, action: any) => { 35 | 36 | switch (action.type) { 37 | case actions.SET_PRODUCTS: 38 | return { 39 | ...state, 40 | } 41 | case actions.ADD_TO_CART: 42 | return { 43 | ...state, 44 | products: getProduct(state, action.payload) 45 | } 46 | default: 47 | return { 48 | ...state 49 | } 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /src/reducers/storeHours.ts: -------------------------------------------------------------------------------- 1 | import { StoreHours } from '../types'; 2 | import { actions } from '../actions/constants'; 3 | 4 | const initialState: StoreHours = { 5 | open: true 6 | } 7 | 8 | export const storeHours = (state = initialState, action: any) => { 9 | 10 | switch (action.type) { 11 | case actions.STORE_OPERATING: 12 | return { 13 | open: !state.open 14 | } 15 | default: 16 | return { 17 | ...state 18 | } 19 | } 20 | }; 21 | -------------------------------------------------------------------------------- /src/serviceWorker.ts: -------------------------------------------------------------------------------- 1 | // This optional code is used to register a service worker. 2 | // register() is not called by default. 3 | 4 | // This lets the app load faster on subsequent visits in production, and gives 5 | // it offline capabilities. However, it also means that developers (and users) 6 | // will only see deployed updates on subsequent visits to a page, after all the 7 | // existing tabs open on the page have been closed, since previously cached 8 | // resources are updated in the background. 9 | 10 | // To learn more about the benefits of this model and instructions on how to 11 | // opt-in, read https://bit.ly/CRA-PWA 12 | 13 | const isLocalhost = Boolean( 14 | window.location.hostname === 'localhost' || 15 | // [::1] is the IPv6 localhost address. 16 | window.location.hostname === '[::1]' || 17 | // 127.0.0.1/8 is considered localhost for IPv4. 18 | window.location.hostname.match( 19 | /^127(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$/ 20 | ) 21 | ); 22 | 23 | type Config = { 24 | onSuccess?: (registration: ServiceWorkerRegistration) => void; 25 | onUpdate?: (registration: ServiceWorkerRegistration) => void; 26 | }; 27 | 28 | export function register(config?: Config) { 29 | if (process.env.NODE_ENV === 'production' && 'serviceWorker' in navigator) { 30 | // The URL constructor is available in all browsers that support SW. 31 | const publicUrl = new URL( 32 | (process as { env: { [key: string]: string } }).env.PUBLIC_URL, 33 | window.location.href 34 | ); 35 | if (publicUrl.origin !== window.location.origin) { 36 | // Our service worker won't work if PUBLIC_URL is on a different origin 37 | // from what our page is served on. This might happen if a CDN is used to 38 | // serve assets; see https://github.com/facebook/create-react-app/issues/2374 39 | return; 40 | } 41 | 42 | window.addEventListener('load', () => { 43 | const swUrl = `${process.env.PUBLIC_URL}/service-worker.js`; 44 | 45 | if (isLocalhost) { 46 | // This is running on localhost. Let's check if a service worker still exists or not. 47 | checkValidServiceWorker(swUrl, config); 48 | 49 | // Add some additional logging to localhost, pointing developers to the 50 | // service worker/PWA documentation. 51 | navigator.serviceWorker.ready.then(() => { 52 | console.log( 53 | 'This web app is being served cache-first by a service ' + 54 | 'worker. To learn more, visit https://bit.ly/CRA-PWA' 55 | ); 56 | }); 57 | } else { 58 | // Is not localhost. Just register service worker 59 | registerValidSW(swUrl, config); 60 | } 61 | }); 62 | } 63 | } 64 | 65 | function registerValidSW(swUrl: string, config?: Config) { 66 | navigator.serviceWorker 67 | .register(swUrl) 68 | .then(registration => { 69 | registration.onupdatefound = () => { 70 | const installingWorker = registration.installing; 71 | if (installingWorker == null) { 72 | return; 73 | } 74 | installingWorker.onstatechange = () => { 75 | if (installingWorker.state === 'installed') { 76 | if (navigator.serviceWorker.controller) { 77 | // At this point, the updated precached content has been fetched, 78 | // but the previous service worker will still serve the older 79 | // content until all client tabs are closed. 80 | console.log( 81 | 'New content is available and will be used when all ' + 82 | 'tabs for this page are closed. See https://bit.ly/CRA-PWA.' 83 | ); 84 | 85 | // Execute callback 86 | if (config && config.onUpdate) { 87 | config.onUpdate(registration); 88 | } 89 | } else { 90 | // At this point, everything has been precached. 91 | // It's the perfect time to display a 92 | // "Content is cached for offline use." message. 93 | console.log('Content is cached for offline use.'); 94 | 95 | // Execute callback 96 | if (config && config.onSuccess) { 97 | config.onSuccess(registration); 98 | } 99 | } 100 | } 101 | }; 102 | }; 103 | }) 104 | .catch(error => { 105 | console.error('Error during service worker registration:', error); 106 | }); 107 | } 108 | 109 | function checkValidServiceWorker(swUrl: string, config?: Config) { 110 | // Check if the service worker can be found. If it can't reload the page. 111 | fetch(swUrl) 112 | .then(response => { 113 | // Ensure service worker exists, and that we really are getting a JS file. 114 | const contentType = response.headers.get('content-type'); 115 | if ( 116 | response.status === 404 || 117 | (contentType != null && contentType.indexOf('javascript') === -1) 118 | ) { 119 | // No service worker found. Probably a different app. Reload the page. 120 | navigator.serviceWorker.ready.then(registration => { 121 | registration.unregister().then(() => { 122 | window.location.reload(); 123 | }); 124 | }); 125 | } else { 126 | // Service worker found. Proceed as normal. 127 | registerValidSW(swUrl, config); 128 | } 129 | }) 130 | .catch(() => { 131 | console.log( 132 | 'No internet connection found. App is running in offline mode.' 133 | ); 134 | }); 135 | } 136 | 137 | export function unregister() { 138 | if ('serviceWorker' in navigator) { 139 | navigator.serviceWorker.ready.then(registration => { 140 | registration.unregister(); 141 | }); 142 | } 143 | } 144 | -------------------------------------------------------------------------------- /src/store/index.ts: -------------------------------------------------------------------------------- 1 | import { createStore } from 'redux'; 2 | import reducers from '../reducers'; 3 | 4 | const store = createStore( 5 | reducers 6 | ); 7 | 8 | export default store -------------------------------------------------------------------------------- /src/styles/_styles.scss: -------------------------------------------------------------------------------- 1 | @import "components/_components"; 2 | @import "containers/_containers"; -------------------------------------------------------------------------------- /src/styles/components/_components.scss: -------------------------------------------------------------------------------- 1 | @import 'productItem'; -------------------------------------------------------------------------------- /src/styles/components/_productItem.scss: -------------------------------------------------------------------------------- 1 | .productItem { 2 | display: flex; 3 | border: solid 1px black; 4 | padding: 20px; 5 | margin: 20px; 6 | &__title { 7 | flex: 1; 8 | } 9 | &__price { 10 | flex: 1; 11 | } 12 | &__quantity { 13 | flex: 1; 14 | } 15 | 16 | } -------------------------------------------------------------------------------- /src/styles/containers/_containers.scss: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/terencejeong/redux-hooks-api-play/32eb8bbb233b6902c00d479930af7ba6f6b93350/src/styles/containers/_containers.scss -------------------------------------------------------------------------------- /src/types/cart.types.ts: -------------------------------------------------------------------------------- 1 | import { Product } from './index'; 2 | export interface Cart { 3 | cart: CartItem[], 4 | isLoading: boolean, 5 | error: boolean 6 | }; 7 | 8 | export interface CartItem { 9 | id: string, 10 | quantityBought: number, 11 | value: number, 12 | title: string, 13 | } 14 | -------------------------------------------------------------------------------- /src/types/index.ts: -------------------------------------------------------------------------------- 1 | export * from './cart.types'; 2 | export * from './products.types'; 3 | export * from './store.types' 4 | export * from './storeHours.types'; 5 | -------------------------------------------------------------------------------- /src/types/products.types.ts: -------------------------------------------------------------------------------- 1 | export interface Product { 2 | id: string, 3 | title: string, 4 | value: number, 5 | quantity: number 6 | } 7 | 8 | export interface Products { 9 | products: Product[], 10 | loading: boolean, 11 | error: boolean 12 | } -------------------------------------------------------------------------------- /src/types/store.types.ts: -------------------------------------------------------------------------------- 1 | import { Cart } from './cart.types'; 2 | import { Products } from './products.types'; 3 | import { StoreHours } from './storeHours.types' 4 | 5 | export interface AppStore { 6 | cartsModule: Cart, 7 | cartsOldModule: Cart, 8 | productsModule: Products, 9 | storeHoursModule: StoreHours, 10 | productsOldModule: Products, 11 | }; -------------------------------------------------------------------------------- /src/types/storeHours.types.ts: -------------------------------------------------------------------------------- 1 | export interface StoreHours { 2 | open: boolean, 3 | } -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "target": "es5", 4 | "lib": [ 5 | "dom", 6 | "dom.iterable", 7 | "esnext" 8 | ], 9 | "allowJs": true, 10 | "skipLibCheck": true, 11 | "esModuleInterop": true, 12 | "allowSyntheticDefaultImports": true, 13 | "strict": true, 14 | "forceConsistentCasingInFileNames": true, 15 | "module": "esnext", 16 | "moduleResolution": "node", 17 | "resolveJsonModule": true, 18 | "isolatedModules": true, 19 | "noEmit": true, 20 | "jsx": "preserve" 21 | }, 22 | "include": [ 23 | "src" 24 | ] 25 | } 26 | --------------------------------------------------------------------------------