pagination is broken after filtering -react.js

331 Views Asked by At

i using react-paginate for pagination system. my problem, there should be 5 item on each page, but it prints all of them on one page, if there are any number of results. here is before and after search img: before and after search

and here is my code

//here is states:
  const [users, setUsers] = useState([])
  const [filteredUsers, setFilteredUsers] = useState([])
  const [searchfield, setSearchfield] = useState('')
  const [userPageCount, setUserPageCount] = useState(0)
  const [userCurrentPage, setUserCurrentPage] = useState(1)


// pagination configs
const displayUsers = (users, setUsers, userCurrentPage) => { 
  const startIndex = (userCurrentPage - 1) * 5
  const endIndex = userCurrentPage * 5
  const productsToDisplay = users.slice(startIndex, endIndex)
  setUsers(productsToDisplay)
}

useEffect(() => { 
    if (searchfield === '') {
      setFilteredUsers(users)
    }
    if (searchfield !== '') {
      let filteredUsers = users.filter((user) => {
        return user.UserID.toLowerCase().includes(searchfield.toLowerCase())
      })
      displayUsers(users, setFilteredUsers, userCurrentPage)
      setUsers(filteredUsers)
      setUserPageCount(Math.ceil(filteredUsers.length / 5))
    }
  }, [searchfield, users, setUsers, displayUsers, userCurrentPage])

 // search function
 const handleSearch = (e) => {
    let searchValue = e.target.value
    let filteredTasks = users.filter((task) => {
      return task.UserID.toLowerCase().includes(searchValue.toLowerCase())
    })
    setUserPageCount(Math.ceil(filteredTasks.length / 5))
    return setFilteredUsers(filteredTasks)
  }

  useEffect(() => {
    displayUsers(users, setFilteredUsers, userCurrentPage)
    setUserPageCount(Math.ceil(users.length / 5))
  }, [users, userCurrentPage, displayUsers, setUserPageCount])

and here is using search component and data mapping area:

 <SearchBox
            placeholder="Search"
            inputfields={(e) => handleSearch(e)}
          />

 {filteredUsers.map((userDetail, index) => {
              const {
                UserID,
                Country,
                City,
                MMA,
                Time,
                Game,
                Revenue,
                Timezone,
                Device_Model,
                Ad_Type,
                Is_Gamepot,
                SubNetwork,
              } = userDetail
0

There are 0 best solutions below