Skip to content

Instantly share code, notes, and snippets.

@vagnerwentz
Created January 25, 2021 10:42
Show Gist options
  • Save vagnerwentz/d34df2dad1e626f0d1bad20b83e5f32c to your computer and use it in GitHub Desktop.
Save vagnerwentz/d34df2dad1e626f0d1bad20b83e5f32c to your computer and use it in GitHub Desktop.
Forum Rocketseat dúvida sobre melhor maneira de fazer.
# API
{
"success":true,
"data":[{...,...}],
"error": null,
}
# Interface StocksProps
interface StocksProps {
id: number;
name: string;
ticker: string;
minimumValue: number;
profitability: number;
favorited: boolean;
}
# States
const [stocks, setStocks] = useState<StocksProps[]>([]);
const [favoriteStock, setFavoriteStock] = useState(false);
# Chamada a API
api.get('stocks').then((response) => {
const stocksDataOrdered = response.data.data.sort(
(stockA: StocksProps, stockB: StocksProps) =>
stockA.name.localeCompare(stockB.name)
).map((stock: StocksProps ) => {
return {
...stock,
favorited: false
}
})
setStocks(stocksDataOrdered);
# handleStockAsFavorite
const handleStockAsFavorite = useCallback((id: number) => {
const stockToChangeTheFavoriteValue = stocks.filter(element => element.id === id);
if (stockToChangeTheFavoriteValue[0].favorited === false) {
setFavoriteStock(true);
return stockToChangeTheFavoriteValue[0].favorited = true;
} else {
setFavoriteStock(false);
return stockToChangeTheFavoriteValue[0].favorited = false;
}
<FavoriteButton onPress={() => handleStockAsFavorite(stock.id)}>
<FavoriteImage source={stock.favorited ? favoritedImg : unfavoriteImg} />
</FavoriteButton>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment