简体   繁体   中英

How To apply filters and pagination in getserversideprops in next js

I am trying to apply filter and pagination on my product list page. but I don't know how to pass values to getServersideprops same as when we fetch data in useEffect and pass the updated values as dependency in react js

Here is my Code Thanks in advance


export const getServerSideProps = async () => {

  const res = await fetch(`http://localhost:4000/api/products?page=1&limit=20&sortBy=price&sortAs=asc`);
  const data = await res.json();

  return {
    props: {productsData: data}
  }
}


function Home({ productsData}) {

  const products =  productsData?.data.products &&  productsData.data.products?.map((item) => {
    return item
  })
  

  return (
    <>
      <h1>Latest Products</h1>
        <Row>
          {products.map((product) => (
            <Col key={product.id} sm={12} md={6} lg={4} xl={3}>
              <Card className="my-3 p-3 rounded">
                <Link href={`/product/${product.id}`}>
                  <Card.Img src={product.image} variant="top" />
                </Link>

                <Card.Body>
                  <Link href={`/product/${product.id}`}>
                    <Card.Title as="div">
                      <strong>{product.name}</strong>
                    </Card.Title>
                  </Link>

                  <Card.Text as="div">
                    <Rating
                      value={product.rating}
                      text={`${product.numReviews} reviews`}
                    />
                  </Card.Text>

                  <Card.Text as="h3">${product.price}</Card.Text>
                </Card.Body>
              </Card>
            </Col>
          ))}
        </Row>
    </>
  );

}


export default Home


You can use URL parameters and get it in getServerSideProps

export async function getServerSideProps({ query }) {
const limit = query.limit;
const page = query.page;
  const res = await fetch(`http://localhost:4000/api/products?page=${page}&limit=${limit}&sortBy=price&sortAs=asc`);
  const data = await res.json();

  return {
    props: {productsData: data,page,limit}
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM