Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

context #8

Open
wants to merge 9 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
46 changes: 5 additions & 41 deletions src/App.jsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import React, { useEffect, useState } from "react";
import React from "react";
import "./App.css";
import Footer from "./Footer";
import Header from "./Header";
Expand All @@ -16,45 +16,11 @@ function App() {
//https://stackoverflow.com/questions/58539813/lazy-initial-state-where-to-use-it
// and https://dmitripavlutin.com/react-usestate-hook-guide/#3-lazy-initialization-of-state
// Or, can use https://www.npmjs.com/package/@rehooks/local-storage which syncs between tabs
const [cart, setCart] = useState(() => {
try {
return JSON.parse(localStorage.getItem("cart")) ?? [];
} catch {
return [];
}
});

// Persist cart in localStorage
useEffect(() => localStorage.setItem("cart", JSON.stringify(cart)), [cart]);

function addToCart(id, size) {
setCart((cart) => {
const alreadyInCart = cart.find((i) => i.id === id && i.size === size);
if (alreadyInCart) {
return cart.map((i) => {
const isMatchingItem = i.id === id && i.size === size;
return isMatchingItem ? { ...i, quantity: i.quantity + 1 } : i;
});
} else {
return [...cart, { id, size, quantity: 1 }];
}
});
}

function updateCart(id, size, quantity) {
setCart((cart) => {
return quantity === 0
? cart.filter((i) => i.id !== id || (i.id === id && i.size !== size))
: cart.map((i) =>
i.id === id && i.size === size ? { ...i, quantity } : i
);
});
}

return (
<>
<div className="content">
<Header cart={cart} />
<Header />

<main>
<Switch>
Expand All @@ -63,14 +29,12 @@ function App() {
</Route>

<Route path="/cart">
<Cart cart={cart} updateCart={updateCart} />
<Cart />
</Route>

<Route
path="/checkout"
render={(reactRouterProps) => (
<Checkout emptyCart={() => setCart([])} {...reactRouterProps} />
)}
render={(reactRouterProps) => <Checkout {...reactRouterProps} />}
/>

<Route path="/confirmation">
Expand All @@ -82,7 +46,7 @@ function App() {
</Route>

<Route path="/:category/:id">
<Detail cart={cart} addToCart={addToCart} />
<Detail />
</Route>
</Switch>
</main>
Expand Down
4 changes: 3 additions & 1 deletion src/Cart.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,10 @@ import React from "react";
import { Link, useHistory } from "react-router-dom";
import useFetchAll from "./services/useFetchAll";
import Loader from "./Loader";
import { useCart } from "./cartContext";

export default function Cart({ cart, updateCart }) {
export default function Cart() {
const { cart, updateCart } = useCart();
// Using ref since not rendered, and need to avoid re-allocating on each render.
const uniqueIdsInCart = [...new Set(cart.map((i) => i.id))];
const requests = uniqueIdsInCart.map((id) => ({ url: `products/${id}` }));
Expand Down
4 changes: 3 additions & 1 deletion src/Checkout.jsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import React, { useState } from "react";
import { useHistory } from "react-router-dom";
import { saveShippingAddress } from "./services/shippingService";
import { useCart } from "./cartContext";

// Declare static data outside the component to avoid needless recreation on each render.
// Challenge: Finish building out the checkout with credit card, billing address, totals.
Expand All @@ -15,7 +16,8 @@ const STATUS = {
SUBMITTING: "SUBMITTING",
};

export default function Checkout({ emptyCart }) {
export default function Checkout() {
const { emptyCart } = useCart();
const history = useHistory();
// Point: When to split vs unify state.
// Tradeoff: unifying makes it easier to send to server, but slightly more work to update.
Expand Down
4 changes: 3 additions & 1 deletion src/Detail.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,10 @@ import { useRouteMatch, Link, useHistory } from "react-router-dom";
import SelectSize from "./SelectSize";
import useFetch from "./services/useFetch";
import Loader from "./Loader";
import { useCart } from "./cartContext";

export default function Detail({ cart, addToCart }) {
export default function Detail() {
const { cart, addToCart } = useCart();
const history = useHistory();
const [size, setSize] = useState("");
const { params } = useRouteMatch();
Expand Down
4 changes: 3 additions & 1 deletion src/Header.jsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
import React from "react";
import { Link, NavLink } from "react-router-dom";
import { useCart } from "./cartContext";

export default function Header({ cart }) {
export default function Header() {
const { cart } = useCart();
return (
<header>
<nav>
Expand Down
72 changes: 72 additions & 0 deletions src/cartContext.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
import React, { useState, useContext, useEffect } from "react";

const CartContext = React.createContext();

export function CartProvider(props) {
const [cart, setCart] = useState(() => {
try {
return JSON.parse(localStorage.getItem("cart")) ?? [];
} catch {
return [];
}
});

// Persist cart in localStorage
useEffect(() => localStorage.setItem("cart", JSON.stringify(cart)), [cart]);

function addToCart(id, size) {
setCart((cart) => {
const alreadyInCart = cart.find((i) => i.id === id && i.size === size);
if (alreadyInCart) {
return cart.map((i) => {
const isMatchingItem = i.id === id && i.size === size;
return isMatchingItem
? {
...i,
quantity: i.quantity + 1,
}
: i;
});
} else {
return [...cart, { id, size, quantity: 1 }];
}
});
}

function updateCart(id, size, quantity) {
setCart((cart) => {
return quantity === 0
? cart.filter((i) => i.id !== id || (i.id === id && i.size !== size))
: cart.map((i) =>
i.id === id && i.size === size ? { ...i, quantity } : i
);
});
}

function emptyCart() {
setCart([]);
}

const contextValue = {
cart,
addToCart,
updateCart,
emptyCart,
};

return (
<CartContext.Provider value={contextValue}>
{props.children}
</CartContext.Provider>
);
}

export function useCart() {
const context = useContext(CartContext);
if (context === undefined) {
throw new Error(
"useCart must be used within a CartProvider. Wrap a parent component in <CartProvider> to fix this error."
);
}
return context;
}
5 changes: 4 additions & 1 deletion src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,15 @@ import ReactDOM from "react-dom";
import App from "./App";
import { BrowserRouter } from "react-router-dom";
import ErrorBoundary from "./ErrorBoundary";
import { CartProvider } from "./cartContext";

ReactDOM.render(
<React.StrictMode>
<ErrorBoundary>
<BrowserRouter>
<App />
<CartProvider>
<App />
</CartProvider>
</BrowserRouter>
</ErrorBoundary>
</React.StrictMode>,
Expand Down