Skip to content

Instantly share code, notes, and snippets.

@flavioribeirojr
Last active April 3, 2020 00:20
Show Gist options
  • Save flavioribeirojr/56d0387677135b7ec38eb0d39e45f177 to your computer and use it in GitHub Desktop.
Save flavioribeirojr/56d0387677135b7ec38eb0d39e45f177 to your computer and use it in GitHub Desktop.
Example of the useDispatch hook
import React from 'react';
import { useDispatch } from 'react-redux';
import { addToCart } from './cart-actions';
const products = [
{
id: 1,
name: 'Coffe Bottle',
price: 29
}
];
function ProductList() {
const dispatch = useDispatch(); // Aqui pedimos para o react-redux pela função dispatch
function addProductToCart(product) {
// Chamamos a função dispatch passando o "payload" retornado pela função addToCart
// algo como { type: 'ADD_TO_CART', product: {...} }
// A função dispatch se responsabiliza por chamar a função respectiva para
// alterar o state da store
dispatch(addToCart(product));
}
return (
<section>
{
products
.map(product => (
<div key={product.id}>
<h1>
Coffe Bottle
</h1>
<button onClick={() => addProductToCart(product)}>
Add to Cart
</button>
</div>
))
}
</section>
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment