├── .editorconfig
├── .gitignore
├── README.md
├── package-lock.json
├── package.json
├── public
├── favicon.ico
├── index.html
├── logo192.png
├── logo512.png
├── manifest.json
└── robots.txt
├── src
├── components
│ ├── App.tsx
│ ├── Nav.tsx
│ ├── ProductsPage.tsx
│ └── shopify
│ │ ├── Cart.tsx
│ │ ├── LineItemComponent.tsx
│ │ ├── ProductComponent.tsx
│ │ ├── Products.tsx
│ │ └── VariantSelector.tsx
├── images
│ └── logo.svg
├── index.tsx
├── react-app-env.d.ts
├── serviceWorker.ts
├── store
│ ├── cartUI
│ │ ├── actions.ts
│ │ ├── reducers.ts
│ │ └── types.ts
│ ├── index.ts
│ ├── shopify
│ │ ├── actions.ts
│ │ ├── reducers.ts
│ │ └── types.ts
│ └── variants
│ │ ├── actions.ts
│ │ ├── reducers.ts
│ │ └── types.ts
├── styles
│ ├── App.css
│ ├── Nav.css
│ ├── index.css
│ └── shopify.css
└── utils
│ └── utils.ts
├── test.md
└── tsconfig.json
/.editorconfig:
--------------------------------------------------------------------------------
1 | root = true
2 |
3 | [*]
4 | end_of_line = lf
5 | indent_style = space
6 | indent_size = 4
7 | charset = utf-8
8 | trim_trailing_whitespace = true
9 | insert_final_newline = true
--------------------------------------------------------------------------------
/.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 | # React + Redux + TypeScript + Shopify's Storefront API Boilerplate Code!
2 |
3 | To get started, clone this repository:
4 |
5 | `git clone https://github.com/princefishthrower/react-redux-typescript-shopify-storefront-api-example.git`
6 |
7 | This app was bootstrapped with `create-react-app`, so it should install just fine with:
8 |
9 | `npm install`
10 |
11 | The only thing to do before running is to add your Shopify store credentials, which are in `src/utils/utils.ts`:
12 |
13 | ```typescript
14 | const client = Client.buildClient({
15 | storefrontAccessToken: 'YOUR_SHOPIFY_STOREFRONT_ACCESS_TOKEN',
16 | domain: 'YOUR_MYSHOPIFY_STORE_URL'
17 | });
18 | ```
19 |
20 | Until you provide proper credentials, you'll see these errors in the console:
21 |
22 | ```
23 | Failed to load resource: net::ERR_NAME_NOT_RESOLVED your_myshopify_store_url/api/2020-07/graphql:1
24 | TypeError: Failed to fetch utils.ts:39
25 | ```
26 |
27 | Run the development site with:
28 |
29 | `npm run start`
30 |
31 | Build a production version with:
32 |
33 | `npm run build`
34 |
35 | This is all described in detail [in a detailed Medium post about this code base](https://medium.com/@frewin.christopher/react-redux-shopify-typescript-boilerplate-f20614bf5bb1). I highly suggest reading that so you know what the heck is going on!
--------------------------------------------------------------------------------
/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "react-redux-shopify-typescript-storefront-api-example",
3 | "version": "0.1.0",
4 | "private": true,
5 | "dependencies": {
6 | "@testing-library/jest-dom": "^4.2.4",
7 | "@testing-library/react": "^9.5.0",
8 | "@testing-library/user-event": "^7.2.1",
9 | "@types/jest": "^24.9.1",
10 | "@types/node": "^12.12.48",
11 | "@types/react": "^16.9.41",
12 | "@types/react-dom": "^16.9.8",
13 | "@types/react-redux": "^7.1.9",
14 | "@types/shopify-buy": "^2.10.1",
15 | "react": "^16.13.1",
16 | "react-dom": "^16.13.1",
17 | "react-redux": "^7.2.0",
18 | "react-scripts": "3.4.1",
19 | "redux": "^4.0.5",
20 | "shopify-buy": "^2.11.0",
21 | "typescript": "^3.7.5"
22 | },
23 | "scripts": {
24 | "start": "react-scripts start",
25 | "build": "react-scripts build",
26 | "eject": "react-scripts eject"
27 | },
28 | "eslintConfig": {
29 | "extends": "react-app"
30 | },
31 | "browserslist": {
32 | "production": [
33 | ">0.2%",
34 | "not dead",
35 | "not op_mini all"
36 | ],
37 | "development": [
38 | "last 1 chrome version",
39 | "last 1 firefox version",
40 | "last 1 safari version"
41 | ]
42 | }
43 | }
44 |
--------------------------------------------------------------------------------
/public/favicon.ico:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/princefishthrower/react-redux-typescript-shopify-storefront-api-example/c209efabc9d65ae3afec1f054e26f3be3cfc3a5a/public/favicon.ico
--------------------------------------------------------------------------------
/public/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
12 |
13 |
17 |
18 |
27 | Redux + Shopify + TypeScript Boilerplate
28 |
29 |
30 |
31 |
32 |
42 |
43 |
44 |
--------------------------------------------------------------------------------
/public/logo192.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/princefishthrower/react-redux-typescript-shopify-storefront-api-example/c209efabc9d65ae3afec1f054e26f3be3cfc3a5a/public/logo192.png
--------------------------------------------------------------------------------
/public/logo512.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/princefishthrower/react-redux-typescript-shopify-storefront-api-example/c209efabc9d65ae3afec1f054e26f3be3cfc3a5a/public/logo512.png
--------------------------------------------------------------------------------
/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 | "src": "logo192.png",
12 | "type": "image/png",
13 | "sizes": "192x192"
14 | },
15 | {
16 | "src": "logo512.png",
17 | "type": "image/png",
18 | "sizes": "512x512"
19 | }
20 | ],
21 | "start_url": ".",
22 | "display": "standalone",
23 | "theme_color": "#000000",
24 | "background_color": "#ffffff"
25 | }
26 |
--------------------------------------------------------------------------------
/public/robots.txt:
--------------------------------------------------------------------------------
1 | # https://www.robotstxt.org/robotstxt.html
2 | User-agent: *
3 | Disallow:
4 |
--------------------------------------------------------------------------------
/src/components/App.tsx:
--------------------------------------------------------------------------------
1 | import React from "react";
2 | import logo from "../images/logo.svg";
3 | import "../styles/App.css";
4 | import "../styles/shopify.css";
5 | import ProductsPage from "./ProductsPage";
6 | import Cart from "./shopify/Cart";
7 | import Nav from "./Nav";
8 | import { bootstrapShopify } from "../utils/utils";
9 |
10 | export default function App() {
11 | // create the shopify client, initialize checkout, retrieve products, etc.
12 | bootstrapShopify();
13 |
14 | return (
15 |
35 | );
36 | }
37 |
--------------------------------------------------------------------------------
/src/components/Nav.tsx:
--------------------------------------------------------------------------------
1 | import React from "react";
2 | import "../styles/Nav.css";
3 | import { setCartOpen } from "../store/cartUI/actions";
4 |
5 | export default function Nav() {
6 | return (
7 |
8 |
9 | -
10 |
11 |
12 | -
13 |
14 |
15 | -
16 |
17 |
18 | -
19 |
20 |
21 | -
22 |
23 |
24 | -
25 |
28 |
29 |
30 |
31 | );
32 | }
33 |
--------------------------------------------------------------------------------
/src/components/ProductsPage.tsx:
--------------------------------------------------------------------------------
1 | import React from "react";
2 | import Products from "./shopify/Products";
3 |
4 | export default function ProductsPage() {
5 | return (
6 |
7 |
Whoa, here's a generic Products Page / Section Title!
8 |
And here's a paragraph tag within the product page!
9 |
And here are your shop's products:
10 |
11 |
12 | );
13 | }
14 |
--------------------------------------------------------------------------------
/src/components/shopify/Cart.tsx:
--------------------------------------------------------------------------------
1 | import * as React from "react";
2 | import LineItem from "./LineItemComponent";
3 | import { RootState } from "../../store";
4 | import { setCartOpen } from "../../store/cartUI/actions";
5 | import { useSelector } from "react-redux";
6 |
7 | export default function Cart() {
8 | const shopify = useSelector((state: RootState) => state.shopify);
9 | const cartUI = useSelector((state: RootState) => state.cartUI);
10 | const { cart } = shopify;
11 | const { isCartOpen } = cartUI;
12 | return (
13 |
14 |
15 | Your cart
16 |
22 |
23 |
24 | {cart?.lineItems.map((lineItem) => {
25 | return (
26 |
30 | );
31 | })}
32 |
33 |
77 |
78 | );
79 | }
80 |
--------------------------------------------------------------------------------
/src/components/shopify/LineItemComponent.tsx:
--------------------------------------------------------------------------------
1 | import * as React from "react";
2 | import { LineItem } from "shopify-buy";
3 | import {
4 | decrementQuantity,
5 | incrementQuantity,
6 | removeLineItemFromCart,
7 | } from "../../store/shopify/actions";
8 |
9 | interface ILineItemProps {
10 | lineItem: LineItem;
11 | }
12 |
13 | export default function LineItemComponent(props: ILineItemProps) {
14 | const { lineItem } = props;
15 | return (
16 |
17 |
18 | {lineItem.image ? (
19 |

23 | ) : null}
24 |
25 |
26 |
27 |
28 | {lineItem.variantTitle}
29 |
30 |
{lineItem.title}
31 |
32 |
33 |
34 |
40 | {lineItem.quantity}
41 |
47 |
48 |
49 | $ {(lineItem.quantity * parseFloat(lineItem.price)).toFixed(2)}
50 |
51 |
57 |
58 |
59 |
60 | );
61 | }
62 |
--------------------------------------------------------------------------------
/src/components/shopify/ProductComponent.tsx:
--------------------------------------------------------------------------------
1 | import React from "react";
2 | import VariantSelector from "./VariantSelector";
3 | import { Product } from "shopify-buy";
4 | import { addVariantToCart } from "../../store/shopify/actions";
5 | import { handleQuantityChange } from "../../store/variants/actions";
6 | import { useSelector } from "react-redux";
7 | import { RootState } from "../../store";
8 |
9 | interface IProductProps {
10 | product: Product;
11 | }
12 |
13 | export default function ProductComponent(props: IProductProps) {
14 | const { product } = props;
15 | const variants = useSelector((state: RootState) => state.variants);
16 | const {
17 | selectedVariant,
18 | selectedVariantImage,
19 | selectedVariantQuantity,
20 | } = variants;
21 | const variantImage = selectedVariantImage || product.images[0];
22 | const variant = selectedVariant || product.variants[0];
23 | const variantQuantity = selectedVariantQuantity || 1;
24 | return (
25 |
26 | {product.images.length ? (
27 |

28 | ) : null}
29 |
{product.title}
30 |
${variant.price}
31 | {product.options.map((option) => {
32 | return
;
33 | })}
34 |
44 |
50 |
51 | );
52 | }
53 |
--------------------------------------------------------------------------------
/src/components/shopify/Products.tsx:
--------------------------------------------------------------------------------
1 | import * as React from "react";
2 | import ProductComponent from "./ProductComponent";
3 | import { useSelector } from 'react-redux';
4 | import { Product } from "shopify-buy";
5 | import { RootState } from "../../store";
6 |
7 | export default function Products() {
8 | const { products } = useSelector((state: RootState) => state.shopify)
9 |
10 | if (products) {
11 | return (
12 |
13 | {products
14 | .map((product: Product) => {
15 | return (
16 |
20 | );
21 | })
22 | .reverse()}
23 |
24 | );
25 | } else {
26 | return Loading...
;
27 | }
28 | }
29 |
--------------------------------------------------------------------------------
/src/components/shopify/VariantSelector.tsx:
--------------------------------------------------------------------------------
1 | import * as React from "react";
2 | import { Option, OptionValue } from "shopify-buy";
3 | import { handleOptionChange } from "../../store/variants/actions";
4 |
5 | interface IVariantSelectorProps {
6 | option: Option
7 | }
8 |
9 | export default function VariantSelector(props: IVariantSelectorProps) {
10 | const { option } = props;
11 | return (
12 |
27 | );
28 | }
29 |
--------------------------------------------------------------------------------
/src/images/logo.svg:
--------------------------------------------------------------------------------
1 |
8 |
--------------------------------------------------------------------------------
/src/index.tsx:
--------------------------------------------------------------------------------
1 | import React from "react";
2 | import ReactDOM from "react-dom";
3 | import "./styles/index.css";
4 | import App from "./components/App";
5 | import * as serviceWorker from "./serviceWorker";
6 | import { Provider } from "react-redux";
7 | import { store } from "./store";
8 |
9 | ReactDOM.render(
10 |
11 |
12 |
13 |
14 | ,
15 | document.getElementById("root")
16 | );
17 |
18 | // If you want your app to work offline and load faster, you can change
19 | // unregister() to register() below. Note this comes with some pitfalls.
20 | // Learn more about service workers: https://bit.ly/CRA-PWA
21 | serviceWorker.unregister();
22 |
--------------------------------------------------------------------------------
/src/react-app-env.d.ts:
--------------------------------------------------------------------------------
1 | ///
2 |
--------------------------------------------------------------------------------
/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.0/8 are 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.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 | headers: { 'Service-Worker': 'script' }
113 | })
114 | .then(response => {
115 | // Ensure service worker exists, and that we really are getting a JS file.
116 | const contentType = response.headers.get('content-type');
117 | if (
118 | response.status === 404 ||
119 | (contentType != null && contentType.indexOf('javascript') === -1)
120 | ) {
121 | // No service worker found. Probably a different app. Reload the page.
122 | navigator.serviceWorker.ready.then(registration => {
123 | registration.unregister().then(() => {
124 | window.location.reload();
125 | });
126 | });
127 | } else {
128 | // Service worker found. Proceed as normal.
129 | registerValidSW(swUrl, config);
130 | }
131 | })
132 | .catch(() => {
133 | console.log(
134 | 'No internet connection found. App is running in offline mode.'
135 | );
136 | });
137 | }
138 |
139 | export function unregister() {
140 | if ('serviceWorker' in navigator) {
141 | navigator.serviceWorker.ready
142 | .then(registration => {
143 | registration.unregister();
144 | })
145 | .catch(error => {
146 | console.error(error.message);
147 | });
148 | }
149 | }
150 |
--------------------------------------------------------------------------------
/src/store/cartUI/actions.ts:
--------------------------------------------------------------------------------
1 | import { SET_CART_OPEN } from "./types";
2 | import { store } from "..";
3 |
4 | export function setCartOpen(isCartOpen: boolean): void {
5 | store.dispatch({
6 | type: SET_CART_OPEN,
7 | payload: {
8 | isCartOpen,
9 | },
10 | });
11 | }
12 |
--------------------------------------------------------------------------------
/src/store/cartUI/reducers.ts:
--------------------------------------------------------------------------------
1 | import { CartUIActionTypes, CartUIState, SET_CART_OPEN } from "./types";
2 |
3 | const initialState: CartUIState = {
4 | isCartOpen: false,
5 | };
6 |
7 | export function cartUIReducer(
8 | state = initialState,
9 | action: CartUIActionTypes
10 | ): CartUIState {
11 | switch (action.type) {
12 | case SET_CART_OPEN:
13 | return { ...state, isCartOpen: action.payload.isCartOpen };
14 | default:
15 | return state;
16 | }
17 | }
18 |
--------------------------------------------------------------------------------
/src/store/cartUI/types.ts:
--------------------------------------------------------------------------------
1 | export const SET_CART_OPEN = "SET_CART_OPEN";
2 |
3 | export interface CartUIState {
4 | isCartOpen: boolean;
5 | }
6 |
7 | export interface SetCartOpenAction {
8 | type: typeof SET_CART_OPEN;
9 | payload: {
10 | isCartOpen: boolean;
11 | };
12 | }
13 |
14 | export type CartUIActionTypes = SetCartOpenAction;
15 |
--------------------------------------------------------------------------------
/src/store/index.ts:
--------------------------------------------------------------------------------
1 | import { createStore, combineReducers } from "redux";
2 | import { shopifyReducer } from "./shopify/reducers";
3 | import { cartUIReducer } from "./cartUI/reducers";
4 | import { variantsReducer } from "./variants/reducers";
5 |
6 | const rootReducer = combineReducers({
7 | shopify: shopifyReducer,
8 | cartUI: cartUIReducer,
9 | variants: variantsReducer,
10 | });
11 |
12 | export type RootState = ReturnType;
13 |
14 | export const store = createStore(rootReducer);
15 |
--------------------------------------------------------------------------------
/src/store/shopify/actions.ts:
--------------------------------------------------------------------------------
1 | import { store } from "..";
2 | import { LineItem } from "shopify-buy";
3 |
4 | export function addVariantToCart(variantId: string | number, quantity: number) {
5 | const { shopify } = store.getState();
6 | const { cart, client } = shopify;
7 | const lineItemsToAdd = [{ variantId, quantity }];
8 | if (cart && client) {
9 | const checkoutId = cart.id;
10 | client.checkout.addLineItems(checkoutId, lineItemsToAdd);
11 | }
12 | }
13 |
14 | export function decrementQuantity(lineItem: LineItem) {
15 | const updatedQuantity = lineItem.quantity - 1;
16 | updateQuantityInCart(lineItem.id, updatedQuantity);
17 | }
18 |
19 | export function incrementQuantity(lineItem: LineItem) {
20 | const updatedQuantity = lineItem.quantity + 1;
21 | updateQuantityInCart(lineItem.id, updatedQuantity);
22 | }
23 |
24 | export function removeLineItemFromCart(lineItemId: string | number) {
25 | const { shopify } = store.getState();
26 | const { cart, client } = shopify;
27 | if (client && cart) {
28 | const checkoutId = cart.id;
29 | client.checkout.removeLineItems(checkoutId, [lineItemId.toString()]);
30 | }
31 | }
32 |
33 | function updateQuantityInCart(id: string | number, quantity: number) {
34 | const { shopify } = store.getState();
35 | const { cart, client } = shopify;
36 | if (client && cart) {
37 | const checkoutId = cart.id;
38 | client.checkout.updateLineItem(checkoutId, [{ id, quantity }]);
39 | }
40 | }
41 |
--------------------------------------------------------------------------------
/src/store/shopify/reducers.ts:
--------------------------------------------------------------------------------
1 | import {
2 | CLIENT_CREATED,
3 | PRODUCTS_FETCHED,
4 | CHECKOUT_CREATED,
5 | SHOP_INFO_FETCHED,
6 | ShopifyState,
7 | ShopifyActionTypes,
8 | } from "./types";
9 |
10 | const initialState: ShopifyState = {
11 | client: null,
12 | cart: null,
13 | products: null,
14 | shop: null,
15 | };
16 |
17 | export function shopifyReducer(
18 | state = initialState,
19 | action: ShopifyActionTypes
20 | ): ShopifyState {
21 | switch (action.type) {
22 | case CLIENT_CREATED:
23 | return { ...state, client: action.payload.client };
24 | case PRODUCTS_FETCHED:
25 | return { ...state, products: action.payload.products };
26 | case CHECKOUT_CREATED:
27 | return { ...state, cart: action.payload.cart };
28 | case SHOP_INFO_FETCHED:
29 | return { ...state, shop: action.payload.shop };
30 | default:
31 | return state;
32 | }
33 | }
34 |
--------------------------------------------------------------------------------
/src/store/shopify/types.ts:
--------------------------------------------------------------------------------
1 | import { Client, Shop, Cart, Product } from "shopify-buy";
2 |
3 | export const CLIENT_CREATED = "CLIENT_CREATED";
4 | export const PRODUCTS_FETCHED = "PRODUCTS_FETCHED";
5 | export const CHECKOUT_CREATED = "CHECKOUT_CREATED";
6 | export const SHOP_INFO_FETCHED = "SHOP_INFO_FETCHED";
7 |
8 | export interface ShopifyState {
9 | client: Client | null;
10 | shop: Shop | null;
11 | cart: Cart | null;
12 | products: Array | null;
13 | }
14 |
15 | export interface ClientCreatedAction {
16 | type: typeof CLIENT_CREATED;
17 | payload: {
18 | client: any;
19 | };
20 | }
21 |
22 | export interface ShopInfoFetchedAction {
23 | type: typeof SHOP_INFO_FETCHED;
24 | payload: {
25 | shop: any;
26 | };
27 | }
28 |
29 | export interface ProductsFetchedAction {
30 | type: typeof PRODUCTS_FETCHED;
31 | payload: {
32 | products: any;
33 | };
34 | }
35 |
36 | export interface CheckoutCreatedAction {
37 | type: typeof CHECKOUT_CREATED;
38 | payload: {
39 | cart: any;
40 | };
41 | }
42 |
43 | export type ShopifyActionTypes =
44 | | ClientCreatedAction
45 | | ProductsFetchedAction
46 | | CheckoutCreatedAction
47 | | ShopInfoFetchedAction;
48 |
--------------------------------------------------------------------------------
/src/store/variants/actions.ts:
--------------------------------------------------------------------------------
1 | import { store } from "..";
2 | import {
3 | SET_SELECTED_VARIANT_QUANTITY,
4 | SET_SELECTED_VARIANT_AND_VARIANT_IMAGE,
5 | } from "./types";
6 |
7 | export function handleQuantityChange(
8 | event: React.ChangeEvent
9 | ) {
10 | store.dispatch({
11 | type: SET_SELECTED_VARIANT_QUANTITY,
12 | payload: {
13 | selectedVariantQuantity: parseFloat(event.target.value),
14 | },
15 | });
16 | }
17 |
18 | export function handleOptionChange(
19 | event: React.ChangeEvent,
20 | product: ShopifyBuy.Product
21 | ) {
22 | const { shopify } = store.getState();
23 | const { client } = shopify;
24 | let selectedOptions: any;
25 | product.options.forEach((selector) => {
26 | selectedOptions[selector.name] = selector.values[0].value;
27 | });
28 |
29 | const target = event.target;
30 | selectedOptions[target.name] = target.value;
31 |
32 | if (client) {
33 | const selectedVariant = client.product.variantForOptions(
34 | product,
35 | selectedOptions
36 | );
37 |
38 | store.dispatch({
39 | type: SET_SELECTED_VARIANT_AND_VARIANT_IMAGE,
40 | payload: {
41 | selectedVariant,
42 | selectedVariantImage: selectedVariant.attrs.image,
43 | },
44 | });
45 | }
46 | }
47 |
--------------------------------------------------------------------------------
/src/store/variants/reducers.ts:
--------------------------------------------------------------------------------
1 | import {
2 | VariantsState,
3 | VariantsActionTypes,
4 | SET_SELECTED_VARIANT_QUANTITY,
5 | SET_SELECTED_VARIANT_AND_VARIANT_IMAGE,
6 | } from "./types";
7 |
8 | const initialState: VariantsState = {
9 | selectedVariantQuantity: null,
10 | selectedVariant: null,
11 | selectedVariantImage: null,
12 | };
13 |
14 | export function variantsReducer(
15 | state = initialState,
16 | action: VariantsActionTypes
17 | ): VariantsState {
18 | switch (action.type) {
19 | case SET_SELECTED_VARIANT_QUANTITY:
20 | return {
21 | ...state,
22 | selectedVariantQuantity: action.payload.selectedVariantQuantity,
23 | };
24 | case SET_SELECTED_VARIANT_AND_VARIANT_IMAGE:
25 | return {
26 | ...state,
27 | selectedVariant: action.payload.selectedVariant,
28 | selectedVariantImage: action.payload.selectedVariantImage,
29 | };
30 | default:
31 | return state;
32 | }
33 | }
34 |
--------------------------------------------------------------------------------
/src/store/variants/types.ts:
--------------------------------------------------------------------------------
1 | export const SET_SELECTED_VARIANT_QUANTITY = "SET_SELECTED_VARIANT_QUANTITY";
2 | export const SET_SELECTED_VARIANT_AND_VARIANT_IMAGE =
3 | "SET_SELECTED_VARIANT_AND_VARIANT_IMAGE";
4 |
5 | export interface VariantsState {
6 | selectedVariantQuantity: number | null;
7 | selectedVariant: ShopifyBuy.ProductVariant | null;
8 | selectedVariantImage: any | null;
9 | }
10 |
11 | export interface SetSelectedVariantQuantityAction {
12 | type: typeof SET_SELECTED_VARIANT_QUANTITY;
13 | payload: {
14 | selectedVariantQuantity: number;
15 | };
16 | }
17 |
18 | export interface SetSelectedVariantAndVariantImageAction {
19 | type: typeof SET_SELECTED_VARIANT_AND_VARIANT_IMAGE;
20 | payload: {
21 | selectedVariant: ShopifyBuy.ProductVariant;
22 | selectedVariantImage: any;
23 | };
24 | }
25 |
26 | export type VariantsActionTypes =
27 | | SetSelectedVariantQuantityAction
28 | | SetSelectedVariantAndVariantImageAction;
29 |
--------------------------------------------------------------------------------
/src/styles/App.css:
--------------------------------------------------------------------------------
1 | .App {
2 | text-align: center;
3 | }
4 |
5 | .App-logo {
6 | height: 40vmin;
7 | pointer-events: none;
8 | }
9 |
10 | @media (prefers-reduced-motion: no-preference) {
11 | .App-logo {
12 | animation: App-logo-spin infinite 20s linear;
13 | }
14 | }
15 |
16 | .App-header {
17 | background-color: #282c34;
18 | min-height: 100vh;
19 | display: flex;
20 | flex-direction: column;
21 | align-items: center;
22 | justify-content: center;
23 | font-size: calc(10px + 2vmin);
24 | color: white;
25 | }
26 |
27 | .App-link {
28 | color: #61dafb;
29 | }
30 |
31 | @keyframes App-logo-spin {
32 | from {
33 | transform: rotate(0deg);
34 | }
35 | to {
36 | transform: rotate(360deg);
37 | }
38 | }
39 |
--------------------------------------------------------------------------------
/src/styles/Nav.css:
--------------------------------------------------------------------------------
1 | .nav ul {
2 | list-style: none;
3 | background-color: #444;
4 | text-align: center;
5 | padding: 0;
6 | margin: 0;
7 | }
8 | .nav li {
9 | font-family: 'Oswald', sans-serif;
10 | font-size: 1.2em;
11 | line-height: 40px;
12 | height: 40px;
13 | border-bottom: 1px solid #888;
14 | }
15 |
16 | .nav a {
17 | text-decoration: none;
18 | color: #fff;
19 | display: block;
20 | transition: .3s background-color;
21 | }
22 |
23 | .nav a:hover {
24 | background-color: #005f5f;
25 | }
26 |
27 | .nav a.active {
28 | background-color: #fff;
29 | color: #444;
30 | cursor: default;
31 | }
32 |
33 | @media screen and (min-width: 600px) {
34 | .nav li {
35 | width: 120px;
36 | border-bottom: none;
37 | height: 50px;
38 | line-height: 50px;
39 | font-size: 1.4em;
40 | }
41 |
42 | /* Option 1 - Display Inline */
43 | .nav li {
44 | display: inline-block;
45 | margin-right: -4px;
46 | }
47 |
48 | /* Options 2 - Float
49 | .nav li {
50 | float: left;
51 | }
52 | .nav ul {
53 | overflow: auto;
54 | width: 600px;
55 | margin: 0 auto;
56 | }
57 | .nav {
58 | background-color: #444;
59 | }
60 | */
61 | }
--------------------------------------------------------------------------------
/src/styles/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/styles/shopify.css:
--------------------------------------------------------------------------------
1 | @import url('https://fonts.googleapis.com/css?family=Roboto:300,400,700');
2 |
3 | *, *:before, *:after {
4 | box-sizing: border-box;
5 | }
6 |
7 | html {
8 | font-size: 65%;
9 | }
10 |
11 | body {
12 | margin: 0;
13 | padding: 0;
14 | font-family: 'Roboto', sans-serif;
15 | font-weight: 400;
16 | }
17 |
18 | img {
19 | display: block;
20 | max-width: 100%;
21 | max-height: 100%;
22 | }
23 |
24 | h1 {
25 | font-weight: 300;
26 | margin: 0 0 15px;
27 | font-size: 3rem;
28 | }
29 |
30 | h2 {
31 | font-weight: 300;
32 | margin: 0;
33 | font-size: 2rem;
34 | }
35 |
36 | /* BASE APP
37 | * ============================== */
38 | .App__header {
39 | background-color: #222;
40 | background-image: url('https://unsplash.it/1000/300?image=823');
41 | background-size: cover;
42 | color: white;
43 | padding: 10px 10px;
44 | }
45 |
46 | .App__nav{
47 | width: 100%;
48 | list-style: none;
49 | }
50 |
51 | .App__customer-actions {
52 | float: left;
53 | padding: 10px;
54 | }
55 |
56 | .App__title {
57 | padding: 80px 20px;
58 | text-align: center;
59 | }
60 |
61 | .Product-wrapper {
62 | max-width: 900px;
63 | margin: 40px auto 0;
64 | display: flex;
65 | flex-wrap: wrap;
66 | justify-content: center;
67 | }
68 |
69 | .App__view-cart-wrapper {
70 | float: right;
71 | }
72 |
73 | .App__view-cart {
74 | font-size: 15px;
75 | border: none;
76 | background: none;
77 | cursor: pointer;
78 | color: white;
79 | }
80 |
81 | .button {
82 | font-family: 'Poppins', sans-serif;
83 | text-transform: uppercase;
84 | background-color: #1A1B2A;
85 | color: white;
86 | border: none;
87 | font-size: 1.2rem;
88 | padding: 10px 17px;
89 | cursor: pointer;
90 | transition: 0.5s;
91 | border: solid #1A1B2A 1px;
92 | }
93 |
94 | .button:hover,
95 | .button:focus {
96 | color: #1A1B2A;
97 | background-color: white;
98 |
99 | transition: 0.5s;
100 | }
101 |
102 | .button:disabled {
103 | background: #bfbfbf;
104 | cursor: not-allowed;
105 | }
106 |
107 | .login {
108 | font-size: 1.2rem;
109 | color: #b8b8b8;
110 | cursor: pointer;
111 | }
112 |
113 | .login:hover {
114 | color: white;
115 | }
116 |
117 | .Flash__message-wrapper {
118 | -webkit-justify-content: center;
119 | -ms-flex-pack: center;
120 | align-items: flex-end;
121 | justify-content: center;
122 | position: fixed;
123 | bottom: 0;
124 | pointer-events: none;
125 | z-index: 227;
126 | left: 50%;
127 | transform: translateX(-50%);
128 | }
129 |
130 | .Flash__message {
131 | background: rgba(0,0,0,0.88);
132 | border-radius: 3px;
133 | box-shadow: 0 2px 4px rgba(0,0,0,0.1);
134 | color: #ffffff;
135 | cursor: default;
136 | display: -webkit-flex;
137 | display: -ms-flexbox;
138 | display: none;
139 | pointer-events: auto;
140 | position: relative;
141 | font-size: 20px;
142 | line-height: 28px;
143 | font-weight: 400;
144 | padding: 10px 20px;
145 | margin: 0;
146 | }
147 |
148 | .Flash__message--open {
149 | display: flex;
150 | }
151 |
152 | /* CART
153 | * ============================== */
154 | .Cart {
155 | z-index: 9999;
156 | position: fixed;
157 | top: 0;
158 | right: 0;
159 | height: 100%;
160 | width: 350px;
161 | background-color: white;
162 | display: flex;
163 | flex-direction: column;
164 | border-left: 1px solid #e5e5e5;
165 | transform: translateX(100%);
166 | transition: transform 0.15s ease-in-out;
167 | }
168 |
169 | @media (pointer:coarse) { // for all phones and tablets, take up full width (leave desktop with 350px)
170 | .Cart {
171 | width: 100%;
172 | }
173 | }
174 |
175 | .Cart--open {
176 | transform: translateX(0);
177 | }
178 |
179 | .Cart__close {
180 | position: absolute;
181 | right: 9px;
182 | top: 8px;
183 | font-size: 35px;
184 | color: #999;
185 | border: none;
186 | background: transparent;
187 | transition: transform 100ms ease;
188 | cursor: pointer;
189 | }
190 |
191 | .Cart__header {
192 | padding: 20px;
193 | border-bottom: 1px solid #e5e5e5;
194 | flex: 0 0 auto;
195 | display: inline-block;
196 | }
197 |
198 | .Cart__line-items {
199 | flex: 1 0 auto;
200 | margin: 0;
201 | padding: 20px;
202 | }
203 |
204 | .Cart__footer {
205 | padding: 20px;
206 | border-top: 1px solid #e5e5e5;
207 | flex: 0 0 auto;
208 | }
209 |
210 | .Cart__checkout {
211 | margin-top: 20px;
212 | display: block;
213 | width: 100%;
214 | }
215 |
216 | .Cart-info {
217 | padding: 15px 20px 10px;
218 | }
219 |
220 | .Cart-info__total {
221 | float: left;
222 | text-transform: uppercase;
223 | }
224 |
225 | .Cart-info__small {
226 | font-size: 11px;
227 | }
228 |
229 | .Cart-info__pricing {
230 | float: right;
231 | }
232 |
233 | .pricing {
234 | margin-left: 5px;
235 | font-size: 16px;
236 | color: black;
237 | }
238 |
239 | /* LINE ITEMS
240 | * ============================== */
241 | .Line-item {
242 | margin-bottom: 20px;
243 | overflow: hidden;
244 | backface-visibility: visible;
245 | min-height: 65px;
246 | position: relative;
247 | opacity: 1;
248 | transition: opacity 0.2s ease-in-out;
249 | }
250 |
251 | .Line-item__img {
252 | width: 65px;
253 | height: 65px;
254 | border-radius: 3px;
255 | background-size: contain;
256 | background-repeat: no-repeat;
257 | background-position: center center;
258 | background-color: #e5e5e5;
259 | position: absolute;
260 | }
261 |
262 | .Line-item__content {
263 | width: 100%;
264 | padding-left: 75px;
265 | }
266 |
267 | .Line-item__content-row {
268 | display: inline-block;
269 | width: 100%;
270 | margin-bottom: 5px;
271 | position: relative;
272 | }
273 |
274 | .Line-item__variant-title {
275 | float: right;
276 | font-weight: bold;
277 | font-size: 11px;
278 | line-height: 17px;
279 | color: #767676;
280 | }
281 |
282 | .Line-item__title {
283 | color: #4E5665;
284 | font-size: 15px;
285 | font-weight: 400;
286 | }
287 |
288 | .Line-item__price {
289 | line-height: 23px;
290 | float: right;
291 | font-weight: bold;
292 | font-size: 15px;
293 | margin-right: 40px;
294 | }
295 |
296 | .Line-item__quantity-container {
297 | border: 1px solid #767676;
298 | float: left;
299 | border-radius: 3px;
300 | }
301 |
302 | .Line-item__quantity-update {
303 | color: #767676;
304 | display: block;
305 | float: left;
306 | height: 21px;
307 | line-height: 16px;
308 | font-family: monospace;
309 | width: 25px;
310 | padding: 0;
311 | border: none;
312 | background: transparent;
313 | box-shadow: none;
314 | cursor: pointer;
315 | font-size: 18px;
316 | text-align: center;
317 | }
318 |
319 | .Line-item__quantity-update-form {
320 | display: inline;
321 | }
322 |
323 | .Line-item__quantity {
324 | color: black;
325 | width: 38px;
326 | height: 21px;
327 | line-height: 23px;
328 | font-size: 15px;
329 | border: none;
330 | text-align: center;
331 | -moz-appearance: textfield;
332 | background: transparent;
333 | border-left: 1px solid #767676;
334 | border-right: 1px solid #767676;
335 | display: block;
336 | float: left;
337 | padding: 0;
338 | border-radius: 0;
339 | }
340 |
341 | .Line-item__remove {
342 | position: absolute;
343 | right: 0;
344 | top: 0;
345 | border: 0;
346 | background: 0;
347 | font-size: 20px;
348 | top: -4px;
349 | opacity: 0.5;
350 | }
351 |
352 | .Line-item__remove:hover {
353 | opacity: 1;
354 | cursor: pointer;
355 | }
356 |
357 | /* PRODUCTS
358 | * ============================== */
359 | .Product {
360 | font-family: 'Poppins', sans-serif;
361 | flex: 0 1 39%;
362 | margin-left: 1%;
363 | margin-right: 1%;
364 | margin-bottom: 3%;
365 | }
366 |
367 | @media (pointer:coarse) {
368 | .Product {
369 | flex: 0 1 98%;
370 | }
371 | }
372 |
373 | .Product__title {
374 | font-size: 1.3rem;
375 | margin-top: 1rem;
376 | margin-bottom: 0.4rem;
377 | opacity: 0.7;
378 | }
379 |
380 | .Product__price {
381 | display: block;
382 | font-size: 1.1rem;
383 | opacity: 0.5;
384 | margin-bottom: 0.4rem;
385 | }
386 |
387 | .Product__option {
388 | display: block;
389 | width: 100%;
390 | margin-bottom: 10px;
391 | }
392 |
393 | .Product__quantity {
394 | display: block;
395 | width: 15%;
396 | margin-bottom: 10px;
397 | }
398 |
399 | /* CUSTOMER AUTH
400 | * ============================== */
401 | .CustomerAuth {
402 | background: #2a2c2e;
403 | display: none;
404 | height: 100%;
405 | left: 0;
406 | opacity: 0;
407 | padding: 0 0 65px;
408 | top: 0;
409 | width: 100%;
410 | text-align: center;
411 | color: #fff;
412 | transition: opacity 150ms;
413 | opacity: 1;
414 | visibility: visible;
415 | z-index: 1000;
416 | position: fixed;
417 | }
418 |
419 | .CustomerAuth--open {
420 | display: block;
421 | }
422 |
423 | .CustomerAuth__close {
424 | position: absolute;
425 | right: 9px;
426 | top: 8px;
427 | font-size: 35px;
428 | color: #999;
429 | border: none;
430 | background: transparent;
431 | transition: transform 100ms ease;
432 | cursor: pointer;
433 | }
434 |
435 | .CustomerAuth__body {
436 | padding: 130px 30px;
437 | width: 700px;
438 | margin-left: auto;
439 | margin-right: auto;
440 | text-align: left;
441 | position: relative;
442 | }
443 |
444 | .CustomerAuth__heading {
445 | font-size: 24px;
446 | font-weight: 500;
447 | padding-bottom: 15px;
448 | }
449 |
450 | .CustomerAuth__credential {
451 | display: block;
452 | position: relative;
453 | margin-bottom: 15px;
454 | border-radius: 3px;
455 | }
456 |
457 | .CustomerAuth__input {
458 | height: 60px;
459 | padding: 24px 10px 20px;
460 | border: 0px;
461 | font-size: 18px;
462 | background: #fff;
463 | width: 100%;
464 | }
465 |
466 | .CustomerAuth__submit {
467 | float: right;
468 | }
469 |
470 | .error {
471 | display: block;
472 | font-size: 15px;
473 | padding: 10px;
474 | position: relative;
475 | min-height: 2.64286em;
476 | background: #fbefee;
477 | color: #c23628;
478 | }
--------------------------------------------------------------------------------
/src/utils/utils.ts:
--------------------------------------------------------------------------------
1 | import { store } from "../store";
2 | import Client from "shopify-buy";
3 | import {
4 | CLIENT_CREATED,
5 | PRODUCTS_FETCHED,
6 | CHECKOUT_CREATED,
7 | SHOP_INFO_FETCHED,
8 | } from "../store/shopify/types";
9 |
10 | export async function bootstrapShopify(): Promise {
11 | try {
12 | // client
13 | const client = Client.buildClient({
14 | storefrontAccessToken: "YOUR_SHOPIFY_STOREFRONT_ACCESS_TOKEN",
15 | domain: "YOUR_MYSHOPIFY_STORE_URL",
16 | });
17 | store.dispatch({ type: CLIENT_CREATED, payload: { client } });
18 |
19 | // products
20 | const products = await client.product.fetchAll();
21 | store.dispatch({
22 | type: PRODUCTS_FETCHED,
23 | payload: {
24 | products,
25 | },
26 | });
27 |
28 | // cart
29 | const cart = await client.checkout.create();
30 | store.dispatch({ type: CHECKOUT_CREATED, payload: { cart } });
31 |
32 | // shop
33 | const shop = await client.shop.fetchInfo();
34 | store.dispatch({ type: SHOP_INFO_FETCHED, payload: { shop } });
35 |
36 | // catch any errors thrown in bootstrapping process
37 | } catch (error) {
38 | // TODO: real error handling here, perhaps to real logs or do something else entirely
39 | console.log(error);
40 | }
41 | }
42 |
--------------------------------------------------------------------------------
/test.md:
--------------------------------------------------------------------------------
1 | ```javascript
2 | import { createStore, combineReducers } from 'redux';
3 | import { shopifyReducer } from './shopify/reducers';
4 | import { cartUIReducer } from './cartUI/reducers';
5 | import { variantsReducer } from './variants/reducers';
6 |
7 | const rootReducer = combineReducers({
8 | shopify: shopifyReducer,
9 | cartUI: cartUIReducer,
10 | variants: variantsReducer,
11 | });
12 |
13 | export type RootState = ReturnType;
14 |
15 | export const store = createStore(
16 | rootReducer
17 | );
18 | ```
--------------------------------------------------------------------------------
/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": "react"
21 | },
22 | "include": [
23 | "src"
24 | ]
25 | }
26 |
--------------------------------------------------------------------------------