Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

ReactJs beginners question filter by year function

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading