Error in querying product image in Sanity e-commerce setup resolved with help from Slack thread.

8 replies
Last updated: Nov 14, 2021
I’ve been working at this issue for a day now and it’s driving me crazy! I’m trying to query a product image (using the sanity e-commerce setup) and I keep getting an error of
ProductDetail.js:39 Uncaught TypeError: Cannot destructure property 'images' of 'details' as it is undefined
. My code is:
Nov 14, 2021, 3:33 PM
const ProductDetail = () => {
    const { id } = useParams();
    const [product, setProduct] = useState({});

    const getProductDetail = async () => {
        const res = await sanityClient.fetch(`*[_id == "${id}"]{
            _id,
            title,
            blurb{
            en
            },
            defaultProductVariant{
                images,
                price
                
              },

    }`);
        setProduct(res[0]);
    };

    useEffect(() => {
        getProductDetail();
    }, []);

    const { defaultProductVariant: details } = product;
    const { images } = details;
    const {
        asset: { _ref: imgSRC },
    } = images[0];

    console.log(imgSRC);
Nov 14, 2021, 3:34 PM
This is probably because your code is run all the way through before the data is fetched. The default value of
product
 is
{}
, which means that
defaultProductVariant
 will be
undefined
 at first, and thus there’s no
images
to destruct from it.
There’s many ways of doing this, but maybe

const { defaultProductVariant: details = { images: [] } } = product;
will at least remove your bug?


https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment#default_values_2
Nov 14, 2021, 3:38 PM
Ahhh! Thank you, got it working. Destructuring is very new to me, thanks for the mozilla link. 🙏
Nov 14, 2021, 3:44 PM
Yeah, it takes some use to get used to, but you’ll get the hang of it!
Nov 14, 2021, 3:48 PM
Ahhh! Thank you, got it working. Destructuring is very new to me, thanks for the mozilla link. 🙏
Nov 14, 2021, 3:44 PM
looks like i also needed to use an if statement to stop my code from running until there was a product state
_if_ (!product.title) _return_ null;
Nov 14, 2021, 3:55 PM
looks like i also needed to use an if statement to stop my code from running until there was a product state
_if_ (!product.title) _return_ null;
Nov 14, 2021, 3:55 PM
Yeah, that sounds right. In this case you would probably want to present some kind of loading state while the product info is fetched
Nov 14, 2021, 3:57 PM

Sanity– build remarkable experiences at scale

The Sanity Composable Content Cloud is the headless CMS that treats content as data to power your digital business. Free to get started, and pay-as-you-go on all plans.

Was this answer helpful?