-
-
Save hugoalmeidahh/bfae0dad1e2e3a46b4ee49c1ec36eb98 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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> | |
) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment