Skip to content

Instantly share code, notes, and snippets.

View henlin417's full-sized avatar

Henry Ling henlin417

View GitHub Profile
@henlin417
henlin417 / CheckoutProduct.js
Last active November 3, 2020 23:06
React Context API Example
import React from 'react';
import './CheckoutProduct.css'
import { useStateValue } from "./StateProvider";
function CheckoutProduct({ id, image, title, price, rating, hideButton }) {
const [{ basket }, dispatch] = useStateValue();
const removeFromBasket = () => {
// remove the item from the basket
dispatch({
@henlin417
henlin417 / reducer.js
Created November 3, 2020 22:32
React Context API Example
export const initialState = {
basket: [],
user: null
};
// Selector
export const getBasketTotal = (basket) =>
basket?.reduce((amount, item) => item.price + amount, 0);
const reducer = (state, action) => {
@henlin417
henlin417 / Product.js
Created November 3, 2020 22:31
React Context API Example
import React from "react";
import "./Product.css";
import { useStateValue } from "./StateProvider";
function Product({ id, title, image, price, rating }) {
const [{ basket }, dispatch] = useStateValue();
const addToBasket = () => {
// dispatch the item into the data layer
dispatch({
@henlin417
henlin417 / Home.js
Last active November 3, 2020 22:29
React Context API Example
import React from "react";
import "./Home.css";
import Product from "./Product";
function Home() {
return (
<div className="home">
<div className="home__container">
<img
className="home__image"