I have a below problem in which filter is not working properly. As per below code, I have some data which i am displaying in table and i have one status column i.e active or inactive. I wanted to filterout table based on the status active or inactive. So, when I tried to filter based on Active, it is working but not working for Inactive status as table goes empty. And same thing happened when I try with Inactive first then it filter out correctly table but this time not working for active status as table goes empty. So, its not retaining state of original data. Overall I wanted to switch between Active & Inactive status.
import React, { useState } from "react";
const initialData = [
{
id: 1,
name: "Mayank Kumar",
email: "mayankkumar@gmail.com",
status: "Active",
},
{
id: 2,
name: "Jitender Kumar",
email: "jitenderskumar@gmail.com",
status: "Inactive",
},
];
const TableDemo = () => {
const [data, setData] = useState(initialData);
const filterData = (value) => {
const filterData = data.filter((item) => item.status === value);
setData(filterData);
};
return (
<div>
<table>
<thead>
<tr>
<th style={{ textAlign: "center" }}>No.</th>
<th style={{ textAlign: "center" }}>Name</th>
<th style={{ textAlign: "center" }}>Email</th>
<th style={{ textAlign: "center" }}>Status</th>
</tr>
</thead>
<tbody>
{data.map((item, index) => {
return (
<tr key={item.id}>
<th scope="row">{index + 1}</th>
<td>{item.name}</td>
<td>{item.email}</td>
<td>{item.status}</td>
</tr>
);
})}
</tbody>
</table>
<label>Status:</label>
<button onClick={() => filterData("Active")}>Active</button>
<button onClick={() => filterData("Inactive")}>Inactive</button>
</div>
);
};
export default TableDemo;
What happens here is when you filter the first time for "Active", you are setting new items without the ones that are "Inactive" so you basically lose the data that way.
In your case, there's no need to store your data inside the state. A better approach would be to store a filter inside the state and then conditionally calculate the values you need on render.
const [filter, setFilter] = useState('All')
// use filteredData to map and render the items
const filteredData = initialData.filter(item => {
if (filter === 'All') {
return true
}
return item.status === filter
})
// use filterData function to set the filter
const filterData = (value) => {
setFilter(value);
};