Search code examples
reactjsjsxconditional-rendering

filtering a list based on criteria selected by the user


I'm trying to filter a list of element based on the year (selected by the user), here it is a picture of the form:

enter image description here

By default "2020" it's the default value and in the lists there are elements equals to this year but I'm not getting those ones nor others elements with different year.

This is my code:

import React, { useState } from "react";
import "./Expenses.css";
import ExpenseItemV3 from "./ExpenseItemV3";
import Card from "../UI/Card";
import ExpenseFilter from "./NewExpense/ExpensesFilter";

const Expenses = (props) => {
  const [filteredYear, setFilteredYear] = useState("2020");
  const filterChangeHandler = (selectedYear) => {
    setFilteredYear(selectedYear);
    console.log("Expenses.js received this value: ");
    console.log(selectedYear);
  };

  return (
    <div>
      <Card className="expenses">
        <ExpenseFilter
          selected={filteredYear}
          onChangeFilter={filterChangeHandler}
        />
        {props.records
          .filter((expense) => expense.date.getFullYear() === filteredYear)
          .map((filteredExpense) => (
            <ExpenseItemV3
              key={filteredExpense.id}
              title={filteredExpense.title}
              amount={filteredExpense.amount}
              date={filteredExpense.date}
            />
          ))}
      </Card>
    </div>
  );
};

export default Expenses;

The line where I'm stuck is this:

{props.records
  .filter((expense) => expense.date.getFullYear() === filteredYear)
  .map((filteredExpense) => (
    <ExpenseItemV3
      key={filteredExpense.id}
      title={filteredExpense.title}
      amount={filteredExpense.amount}
      date={filteredExpense.date}
    />
  ))}

So, I don't know what am I missing in order to filter the list (props.records); any hints will be highly appreciated

Thanks a lot


Solution

  • The triple equal sign means not only value but data type has to be the same. Can you confirm that expense.date.getFullYear() returns a string type via a console.log(typeof expense.date.getFullYear()) Becouse im pretty sure getFullYear() returns a number not a string. So you would have to do expense.date.getFullYear().toString() === filteredYear because your filteredYear is set as a string type of a value of 2020 – Lith 26