I am watching a tutorial about Sanity and everything seems fine with the code, but there is something I don't understand. I checked my code for like 6 times and I just don't get it.
Here is my code:
import React from 'react';
import { client, urlFor } from '../../lib/client';
const ProductDetails = ({ product, products }) => {
const { image, name, details, price } = product;
return (
<div>
<div className="product-detail-container">
<div>
<div className="image-container">
<img src={urlFor(image && image[0])} />
</div>
</div>
</div>
</div>
);
};
export const getStaticPaths = async () => {
const query = `*[_type == "product"] {
slug {
current
}
}
`;
const products = await client.fetch(query);
const paths = products.map((product) => ({
params: {
slug: product.slug.current
}
}));
return {
paths,
fallback: 'blocking'
}
}
export const getStaticProps = async ({ params: { slug }}) => {
const query = `*[_type == "product" && slug.current == '${slug}'][0]`;
const productsQuery = '*[_type == "product"]'
const product = await client.fetch(query);
const products = await client.fetch(productsQuery);
return {
props: { products, product }
}
}
export default ProductDetails
I tried everything I know, but it doesn't seem to be working
CodePudding user response:
As the error points out, null
is being passed as the value of the product
prop of the ProductDetails
component.
Perhaps this is a transitory state. In that case, you can use the nullish coalescing operator (??
) to prevent this error:
const ProductDetails = ({ product, products }) => {
const { image, name, details, price } = product ?? {}; // <-- changed here
With such operator, when product
is null
, the destructuring will no longer error, and the variables image
, name
, etc., will be undefined
.