Skip to content

Instantly share code, notes, and snippets.

@natafaye
Created February 22, 2022 21:05
Show Gist options
  • Save natafaye/70abaa51e4e39e120f2f9aa089a4f798 to your computer and use it in GitHub Desktop.
Save natafaye/70abaa51e4e39e120f2f9aa089a4f798 to your computer and use it in GitHub Desktop.
import React from 'react';
import { PropTypes } from 'prop-types';
import { useSelector } from 'react-redux';
/**
* Shows a category name and the number of transactions in that category
* Expects to go inside a <ul> with the class "list-group"
*
* @component
* @example
* const category2 = {
* id: 2,
* name: 'Groceries',
* target: 400,
* };
* <ul className="list-group">
* <CategoryTransactionsNumber category={category2} />
* </ul>
*/
function CategoryTransactionsNumber({ category }) {
// Select count of all transactions from category
const numberOfTransactions = useSelector(
(state) => state.transactions.entities.filter(
(transaction) => transaction.categoryId === category.id,
).length,
);
return (
<li className="list-group-item d-flex justify-content-between align-items-center">
{ category.name }
<span className="badge bg-primary rounded-pill">{ numberOfTransactions }</span>
</li>
);
}
CategoryTransactionsNumber.propTypes = {
/**
* The category to display the name and # of transactions of
*/
category: PropTypes.exact({
id: PropTypes.number.isRequired,
name: PropTypes.string.isRequired,
target: PropTypes.number.isRequired,
}).isRequired,
};
export default CategoryTransactionsNumber;
import React from 'react';
import { useDispatch } from 'react-redux';
import CategoryTransactionsNumber from './budget/CategoryTransactionsNumber';
import { addTransaction } from './transactions/TransactionSlice';
export default function TestPage() {
const dispatch = useDispatch();
const category1 = {
id: 1,
name: 'Rent',
target: 1500,
};
const category2 = {
id: 2,
name: 'Groceries',
target: 400,
};
const addACategory1Transaction = () => {
const transaction = {
categoryId: 1,
};
dispatch(addTransaction(transaction));
};
return (
<ul className="list-group">
Testing
<button type="button" onClick={addACategory1Transaction}>Add Category 1 Transaction</button>
<CategoryTransactionsNumber category={category1} />
<CategoryTransactionsNumber category={category2} />
</ul>
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment