Skip to content

Instantly share code, notes, and snippets.

@hugoalmeidahh
Forked from diego3g/context.tsx
Created June 22, 2021 23:10
Show Gist options
  • Save hugoalmeidahh/bfae0dad1e2e3a46b4ee49c1ec36eb98 to your computer and use it in GitHub Desktop.
Save hugoalmeidahh/bfae0dad1e2e3a46b4ee49c1ec36eb98 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>
)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment