I have student data. I want to filter and display names and IDs based on date. I can select the date but once I choose a date the dropdown menu shows only that particular date, not the other dates. I want to see all the dates whenever I click the input field. Could you please guide me on what I am doing wrong in my code?
const students = [
{
id: 1,
name: "Tobe",
jdate: "12/2/2021",
},
{
id: 2,
name: "Nina",
jdate: "15/2/2021",
},
{
id: 3,
name: "Mike",
jdate: "12/2/2021",
},
{
id: 4,
name: "Scott",
jdate: "14/2/2021",
},
{
id: 5,
name: "Carlos",
jdate: "13/2/2021",
},
]
function App() {
const [filterStudent, setFilterStudent] = useState(students);
const[jDate, setJDate] = useState("")
const dates = Array.from(
new Set(filterStudent.map(st => st.jdate))
)
useEffect(() => {
setFilterStudent(
filterStudent.filter(st => {
return (
(!jDate || jDate === st.jdate) )
})
)
}, [jDate])
return (
<div className="App">
<div>
<select onChange={e => setJDate(e.target.value)} value={jDate}>
<option value="" disabled default selected>
Select Date
</option>
{dates.map(dt => {
return <option key={dt}>{dt}</option>
})}
</select>
</div>
<ul>
{filterStudent.map(st => {
const { name, id, date} = st
return (
<li key={id}>
<div>
Name: <strong>{name}</strong>
</div>
<div>ID: {id}</div>
<div>Joining Date: {date}</div>
</li>
)
})}
</ul>
</div>
)
}
In the 2nd image, I want to see all the dates.
>Solution :
In Line36 : replace students
instead of filterStudent
:
const dates = Array.from(new Set(students.map((st) => st.jdate)));
filteredStudent's
dates just contains selected date
but students
array contains all of dates!!!
Is that what you want meant?