Displaying the data issue on search and filtering in react



I have created dummy users data and displayed it in the table format.

It contains search and filtering of the data(should consider the entire data set not based on the current page data).

Disabled pagination on displaying the filtering/search results. Here search, filtering function works fine on the 1st page. But when I tried to do a search/ filter on the second page, it displays no data found instead of the filtered results.

When I log the search/filter function results, it displays the proper result in the console, but it is not displaying in the table.

I’m not able to fix the issue. Here is the link to codesandbox.

Answer

Your data flow is not correct. Let’s review it together:

The pagination working properly, the getPaginatedData will get the proper data to show on your table. so far so good, but when you change the page pagination, the getPaginatedData will not be saved anywhere. this handler only returns the data on the table and there isn’t any user to search in their name.

To solve the issue, I recommend using another state variable with another useEffect hook to control the page pagination and data (lead to get proper data on search).

You need to implement something like this:

// rest of the codes ...

const [currentPage, setCurrentPage] = useState(1);

const [tableData, setTableData] = useState([]);

useEffect(() => {
    const startIndex = currentPage * dataLimit - dataLimit;
    const endIndex = startIndex + dataLimit;
    const result =  users.slice(startIndex, endIndex);
    
    setTableData(result))

}, [currentPage])

// rest of the codes ...

Now with every change with the page number (pagination), this useEffect hook will trigger and set the proper data to show on the table, then you can use the tableData on your search filter instead of the user data.



Source: stackoverflow