my items format:
{
id: "e4",
title: "New Desk (Wooden)",
amount: 450,
date: new Date(2021, 5, 12),
}
I’m trying to create a filter by year function
const Expenses = ({ items }) => {
const [year, setYear] = useState("");
const [yearFilter, setYearfilter] = useState(false);
const yearFilterHandler = (selectedYear) => {
setYear(selectedYear);
setYearfilter(true);
};
return (
<div>
<ExpensesFilter selected={year} onFilterHandler={yearFilterHandler} />
//Filter by selected year
{yearFilter &&
items
.filter((item) => item.date.getFullYear() === {year})
.map((expense) => (
<ExpenseItem
key={expense.id}
title={expense.title}
amount={expense.amount}
date={expense.date}
/>
))}
{!yearFilter &&
items.map((expense) => (
<ExpenseItem
key={expense.id}
title={expense.title}
amount={expense.amount}
date={expense.date}
/>
))}
</div>
);
I have no idea what’s wrong with the following code, it doesn’t work
items.filter((item) => item.date.getFullYear() === {year})
but I think my logic is correct when I hard code a year inside it works
items.filter((item) => item.date.getFullYear() === 2021)
>Solution :
The main issue here is the fact that you are creating an object with a property name of year and the value of the content of the variable year.
In order to resolve, just remove the curly braces around the year variable:
items.filter(item => item.date.getFullYear() === parseInt(year))