'update match params react router v5

i am doing an admin dashboard with pagination in React. I am having a problem. When user refresh page (f5), assume they are in page 2, when they reload url still is http://localhost:3000/admin/userlist/2 but in pagination it still page 1 enter image description here

I try this code to detect when user reload then push them to page 1 to fit with paginate component but it doenst work!Below is my userlist component

const UserListScreen = ({ history, match }) => {
  const dispatch = useDispatch()
  const pageNumber = match.params.pageNumber || 1

  const userList = useSelector(state => state.userList)
  const { loading, error, users, page, pages } = userList

  const userLogin = useSelector(state => state.userLogin)
  const { userInfo } = userLogin

  const userDelete = useSelector(state => state.userDelete)
  const { success: successDelete } = userDelete

  useEffect(() => {
    if (userInfo && userInfo.isAdmin) {
      dispatch(listUsers(pageNumber))
    } else {
      history.push('/login')
    }

  }, [dispatch, history, successDelete, userInfo, pageNumber])
  useEffect(() => {
    window.onbeforeunload = function () {
      history.push('/admin/userlist/1')
    };
    return () => {
      window.onbeforeunload = null;
    };
  }, []);
  const deleteHandler = (id) => {
    if (window.confirm('Are you sure you want to delete this user?')) {
      dispatch(deleteUser(id))
    }
  }

  return (
    <>
      <h1>User</h1>
      {loading ? <Loader /> : error ? <Message variant='error'>{error}</Message> : (
        <TableContainer>
          <Table striped bordered hover responsive className='table-sm'>
            <thead>
              <tr>

                <ThComponent>Name</ThComponent>
                <ThComponent>Phone</ThComponent>
                <ThComponent>Email</ThComponent>
                <ThComponent>Admin</ThComponent>
                <ThComponent>ACTION</ThComponent>
              </tr>
            </thead>
            <tbody>
              {users.map(user => (
                <tr key={user._id} style={{ background: 'white' }}>

                  <TdComponent>{user.name}</TdComponent>
                  <TdComponent>{user.phoneNumber}</TdComponent>
                  <TdComponent><a href={`mailto:${user.email}`}> {user.email}</a></TdComponent>
                  <TdComponent>
                    {user.isAdmin ? (<CheckCircleRoundedIcon sx={{ color: 'green' }} />) : (<HighlightOffRoundedIcon sx={{ color: 'red' }} />)}
                  </TdComponent>
                  <TdComponent>
                    <LinkContainer to={`/admin/user/${user._id}/edit`}>
                      <Button variant='light' >
                        <ModeEditOutlineRoundedIcon sx={{ color: 'blue' }} />
                      </Button>
                    </LinkContainer>
                    <Button className='ml-2' style={{ background: 'white', borderColor: 'green' }} onClick={() => deleteHandler(user._id)}>
                      <DeleteForeverRoundedIcon sx={{ color: 'green' }} />
                    </Button>
                  </TdComponent>
                </tr>
              ))}
            </tbody>
          </Table>
        </TableContainer>
      )}
      <Paginate page={page} pages={pages} isProduct={false} isUsers={true} isAdmin={true} productList={users} />
    </>
  )
}

export default UserListScreen

and this is paginate component

const Paginate = ({ pages, page, isAdmin = false, keyword = '', productList, isProduct = true, isUsers = false, isOrders = false }) => {
    const history = useHistory()
    const [pageCurr, setPageCurr] = useState(1)
   
    const handleArrowButton = (arrow) => {
        if (arrow === -1) {
            setPageCurr(prevState => prevState - 1)
         
            if (!isAdmin) {
                if (keyword) {
                    history.push(`/search/${keyword}/page/${page - 1}`)
                } else {
                    history.push(`/page/${page - 1}`)
                }
            } else {
                if (isProduct) {
                    history.push(`/admin/productlist/${page - 1}`)
                }
                if (isOrders) {
                    history.push(`/admin/orderlist/${page - 1}`)
                }
                if (isUsers) {
                    history.push(`/admin/userlist/${page - 1}`)
                }
            }

        }
        if (arrow === 1) {
            setPageCurr(prevState => prevState + 1)
         
            if (!isAdmin) {
                if (keyword) {
                    history.push(`/search/${keyword}/page/${page + 1}`)
                } else {
                    history.push(`/page/${page + 1}`)
                }
            } else {
                if (isProduct) {
                    history.push(`/admin/productlist/${page + 1}`)
                }
                if (isOrders) {
                    history.push(`/admin/orderlist/${page + 1}`)
                }
                if (isUsers) {
                    history.push(`/admin/userlist/${page + 1}`)
                }
            }

        }
    }
    
    return pages >= 1 && (
        <>
            <PaginationContainer>
                <ArrowComponent onClick={() => handleArrowButton(-1)} style={{ pointerEvents: pageCurr === 1 ? 'none' : 'inherit' }} disabled={pageCurr === 1}>
                    <ArrowBackIosRoundedIcon sx={{ color: pageCurr === 1 ? '#ccc' : 'black', fontSize: 14 }} />
                </ArrowComponent>
                {isProduct && [...Array(pages).keys()].map(x => (
                    <LinkContainer key={x + 1} to={!isAdmin ? keyword ? `/search/${keyword}/page/${x + 1}` : `/page/${x + 1}` : `/admin/productlist/${x + 1}`} style={{ background: x + 1 === pageCurr ? '#ccc' : 'white' }}>
                        <PaginateItem onClick={() => setPageCurr(x + 1)}>{x + 1}</PaginateItem>
                    </LinkContainer>
                ))}
                {isUsers && [...Array(pages).keys()].map(x => (
                    <LinkContainer key={x + 1} to={isAdmin ? `/admin/userlist/${x + 1}` : `/`} style={{ background: x + 1 === pageCurr ? '#ccc' : 'white' }}>
                        <PaginateItem onClick={() => setPageCurr(x + 1)}>{x + 1}</PaginateItem>
                    </LinkContainer>
                ))}
                {isOrders && [...Array(pages).keys()].map(x => (
                    <LinkContainer key={x + 1} to={isAdmin ? `/admin/orderlist/${x + 1}` : `/`} style={{ background: x + 1 === pageCurr ? '#ccc' : 'white' }}>
                        <PaginateItem onClick={() => setPageCurr(x + 1)}>{x + 1}</PaginateItem>
                    </LinkContainer>
                ))}
                <ArrowComponent onClick={() => handleArrowButton(1)} style={{ pointerEvents: pageCurr === pages || productList.length === 0 ? 'none' : 'inherit' }} disabled={pageCurr === pages || productList.length === 0}>
                    <ArrowForwardIosRoundedIcon sx={{ color: pageCurr === pages || productList.length === 0 ? '#ccc' : 'black', fontSize: 14 }} />
                </ArrowComponent>
            </PaginationContainer>
        </>

    )
}

export default Paginate

Does anyone have any idea how to solve this problem? Thank you!



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source