S
S
semki0962020-08-24 15:12:26
React
semki096, 2020-08-24 15:12:26

How to work with the getStaticProps Next.js function (on my example)?

next.js. As far as I understand, getStaticProps is launched during assembly, inside we get the necessary data, cache it and return this data. When you run this function again, we simply give the data from the cache. Do I understand the algorithm correctly?

If so, then the question is.
There is a products page with all products

export default function Products({ products }) {
  const router = useRouter();
  return ( ... выводим список товаров )
}
export async function getStaticProps() {
  const response = await fetch('http://localhost:3000/api/products');
  const products = await response.json();
  return { props: {products} };
}


There is a product page for a specific product
export default function Product({product}){
    return( ... выводим конкретный товар )
}
export async function getStaticPaths() {
  const res = await fetch('http://localhost:3000/api/products')
  const products = await res.json()
  const paths = products.map((product) => `/product/${product.id}`)
  return { paths, fallback: false }
  }
  export async function getStaticProps({ params }) {
    const res = await fetch(`http://localhost:3000/api/products/${params.id}`)
    const product = await res.json()
    return { props: { product } }
  }


The question itself. On the page of all products I have a modal window. When you click on "Details" - a modal window opens (I pass the product id to the modal window component).
<Modal 
        isOpen={!!router.query.id}
        как сюда передать данные товара на который кликнули?
>
        здесь данные товара на который кликнули

</Modal>

How to get the data of this product in the modal window now? Call getStaticProps again? Surely I'm stupid, tell me how to do it right, thanks!

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
AlexlMl, 2020-08-25
@semki096

getStaticProps - needed to create statics, not caching. getStaticProps is needed to create the final html file.
Send all the necessary data to the madal window props yourself.
You wrapped getStaticProps in getStaticPaths and export it, maybe you don't need it like this :)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question