Skip to content

Instantly share code, notes, and snippets.

@biniama
Last active December 3, 2023 18:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save biniama/77c6b6054c693f730c4e80d8df6bded1 to your computer and use it in GitHub Desktop.
Save biniama/77c6b6054c693f730c4e80d8df6bded1 to your computer and use it in GitHub Desktop.
ReactJS Context API
npm create vite@latest
cd react-hooks-kidu/
npm i
npm i axios
npm run dev
import React, { useState, useEffect, useContext } from 'react'
import './App.css'
import axios from 'axios';
import { CartContext } from './CartContext';
import Cart from './Cart';
import CartNoContext from './CartNoContext';
const App = () => {
const [count, setCount] = useState(0)
// const [color, setColor] = useState("red");
const [text, texty] = useState("My favorite color is red!");
const [callApi, setCallApi] = useState(false);
// useEffect(
// () => {}
// ,
// []
// )
useEffect(
() => {
if (callApi === true) {
axios.get('https://jsonplaceholder.typicode.com/posts/1')
.then((response) => {
console.log(JSON.stringify(response))
})
.catch((error) => { console.error(error) })
} else {
console.log("API is not called")
}
}
,
// [] // when left empty, it executes the call back function inside the useEffect WHEN THE PAGE LOADS
[callApi]
)
const { cart, removeFromCart } = useContext(CartContext);
// console.log(`cart count ${cart.length}`)
// cart.map((price, cakeName) => {
// console.log(`${JSON.stringify(price)} ${cakeName}`)
// })
return (
<>
<button onClick={() => setCallApi(true)}>
Call API
</button>
<hr/>
<h1>Cart</h1>
{cart !== null && cart.map((item) =>
<div className="card" style={{border: 1, borderColor: "green", borderStyle: "dashed"}}>
{item?.cakeName}, ${item?.price}
<button onClick={() => removeFromCart(item?.cakeName)}>
remove
</button>
<br/>
</div>
)}
<hr/>
<Cart />
<hr/>
{/* <CartNoContext length={cart.length}/> */}
<>
<h1>{text}</h1>
<button
type="button" onMouseEnter={() => texty("Hay")} onMouseLeave={() => texty("bye")} onKeyUp={() => texty("keyboard is pressed")}
onClick={() => texty("My color is blue!")}
>Blue</button>
<button
type="button"
onClick={() => texty("I love yellow!")}
>Yellow</button>
</>
<div className="card">
<button onClick={() => setCount((count) => ++count)}>
{/* <button onClick={() => setCount((count) => count + 1)}> */}
count is {count}
</button>
</div>
</>
)
}
export default App
import { useContext } from "react"
import { CartContext } from "./CartContext"
const Cart = () => {
const { cart, addToCart } = useContext(CartContext)
return (
<>
<h1>Product List</h1>
<h5>Cart contains {cart !== null && cart.length} items</h5>
{/* {cart.map((item) =>
<p>{item.cakeName} {item.price}</p>
)} */}
<br />
{/* {addToCart({price: 1, cakeName: 'Kidu'})} */}
{/* <button onClick={() => addToCart(13, 'BlackForest')}>
add to cart
</button> */}
<div className="card" style={{border: 1, borderColor: "green", borderStyle: "dashed"}}>
White Forest
<br/>
<button onClick={() => addToCart(10, 'White Forest')}>
add to cart
</button>
</div>
<div className="card" style={{border: 1, borderColor: "green", borderStyle: "dashed"}}>
Black Forest
<br/>
<button onClick={() => addToCart(5, 'Black Forest')}>
add to cart
</button>
</div>
</>
)
}
export default Cart
import React, { createContext, useState, useEffect } from 'react';
export const CartContext = createContext();
const CartContextProvider = (props) => {
// const [cart, setCart] = useState([
// {price: 10, cakeName: 'Black Forest'},
// {price: 5, cakeName: 'White Forest'},
// ]);
const [cart, setCart] = useState(
JSON.parse(localStorage.getItem('cart')) || null
);
const addToCart = (price, cakeName) => {
if (cart === null) {
setCart([{ price, cakeName }]);
} else {
setCart([...cart, { price, cakeName }]);
}
// add the price and cakeName to localstorge
// setter
// localStorage.setItem('cart', JSON.stringify({'price':price, 'cakeName':cakeName}))
};
const removeFromCart = (cakeName) => {
setCart(cart.filter(cart => cart.cakeName !== cakeName));
}
useEffect(() => {
cart !== null &&
localStorage.setItem('cart', JSON.stringify([...cart]))
}, [cart]);
return (
<CartContext.Provider value={{ cart, addToCart, removeFromCart }}>
{props.children}
</CartContext.Provider>
);
}
export default CartContextProvider;
import { useContext } from "react"
import { CartContext } from "./CartContext"
const CartNoContext = ({length}) => {
return (
<>
OLD {length}
</>
)
}
export default CartNoContext
import React from 'react'
import ReactDOM from 'react-dom/client'
import App from './App.jsx'
import './index.css'
import CartContextProvider from './CartContext.jsx'
ReactDOM.createRoot(document.getElementById('root')).render(
<React.StrictMode>
<CartContextProvider>
<App />
</CartContextProvider>
</React.StrictMode>,
)
{
"name": "react-hooks-kidu",
"private": true,
"version": "0.0.0",
"type": "module",
"scripts": {
"dev": "vite",
"build": "vite build",
"lint": "eslint . --ext js,jsx --report-unused-disable-directives --max-warnings 0",
"preview": "vite preview"
},
"dependencies": {
"axios": "^1.6.2",
"react": "^18.2.0",
"react-dom": "^18.2.0"
},
"devDependencies": {
"@types/react": "^18.2.37",
"@types/react-dom": "^18.2.15",
"@vitejs/plugin-react": "^4.2.0",
"eslint": "^8.53.0",
"eslint-plugin-react": "^7.33.2",
"eslint-plugin-react-hooks": "^4.6.0",
"eslint-plugin-react-refresh": "^0.4.4",
"vite": "^5.0.0"
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment