What I want is to paginate my data but the problem is when I’m searching for specific data if I’m on page 3 the result shows on page 1 always and I can’t see anything because I was on page no 3. I want to go to page 1 automatically when I’m searching for something. Also when I press the next button if there is no data at all it still increases the page number.
Here is my code:
JavaScript
x
59
59
1
import { React, useState, useEffect } from "react";
2
import UpdateDialogue from "./UpdateDialogue";
3
4
function List(props) {
5
const API_URL = "http://dummy.restapiexample.com/api/v1/employees";
6
const [EmployeeData, setEmployeeData] = useState([]);
7
const [pageNumber, setPageNumber] = useState(1);
8
const [postNumber] = useState(8);
9
10
const currentPageNumber = pageNumber * postNumber - postNumber;
11
12
const handlePrev = () => {
13
if (pageNumber === 1) return;
14
setPageNumber(pageNumber - 1);
15
};
16
const handleNext = () => {
17
setPageNumber(pageNumber + 1);
18
};
19
20
useEffect(() => {
21
fetch(API_URL)
22
.then((response) => response.json())
23
.then((response) => {
24
setEmployeeData(response.data);
25
})
26
.catch((err) => {
27
console.error(err);
28
});
29
}, []);
30
31
const filteredData = EmployeeData.filter((el) => {
32
if (props.input === "") {
33
return el;
34
} else {
35
return el.employee_name.toLowerCase().includes(props.input)
36
}
37
});
38
39
const paginatedData = filteredData.splice(currentPageNumber, postNumber);
40
41
return (
42
<>
43
<ul>
44
45
{paginatedData.map((user) => (
46
<UpdateDialogue user={user} key={user.id} />
47
))}
48
</ul>
49
<div>Page {pageNumber} </div>
50
<div>
51
<button style={{marginRight:10}} onClick={handlePrev}>prev</button>
52
<button onClick={handleNext}>next</button>
53
</div>
54
</>
55
);
56
}
57
58
export default List;
59
Advertisement
Answer
Maybe with a useEffect on your input:
JavaScript
1
5
1
useEffect(() => {
2
if (props.input) {
3
setPageNumber(1);
4
}
5
}, [props.input]);
That way, whenever your input changes, your page number is set to 1.