Skip to content

Instantly share code, notes, and snippets.

@diego3g
Created June 22, 2021 22:39
Show Gist options
  • Save diego3g/142a2a86de5356d074674ac0a91dcf27 to your computer and use it in GitHub Desktop.
Save diego3g/142a2a86de5356d074674ac0a91dcf27 to your computer and use it in GitHub Desktop.
import { useState, createContext, useContext } from 'react'
// Lift state up -> Levantar o estado
// Context API
// Prop Drilling
type CartContextType = {
productsInCart: string[];
addProductToCart: (name: string) => void;
}
const CartContext = createContext({} as CartContextType);
function ProductItem(props) {
const { addProductToCart } = useContext(CartContext)
return (
<li>
{props.name}
<button onClick={() => addProductToCart(props.name)}>
Adicionar
</button>
</li>
)
}
function ProductList(props) {
return (
<ul>
<ProductItem name="Product 1" />
<ProductItem name="Product 2" />
<ProductItem name="Product 3" />
<ProductItem name="Product 4" />
<ProductItem name="Product 5" />
</ul>
);
}
function Cart(props) {
const { productsInCart } = useContext(CartContext)
return (
<ul></ul>
);
}
function App() {
const [productsInCart, setProductsInCart] = useState([])
function addProductToCart(product: string) {
setProductsInCart([...productsInCart, product]);
}
return (
<CartContext.Provider value={{ productsInCart, addProductToCart }}>
<OutroContext.Provider value={{ productsInCart, addProductToCart }}>
<MaisUmContext.Provider value={{ productsInCart, addProductToCart }}>
<ProductList />
<Cart />
</MaisUmContext.Provider>
</OutroContext.Provider>
</CartContext.Provider>
)
}
@renatomc
Copy link

Diegão monstro!!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment