Implementing ItemDetailPage using axios to call http://localhost:5001/products/${id} API. Cannot destructure property ‘prodImageURL’ of ‘product’ as it is null.
TypeError: Cannot destructure property ‘prodImageURL’ of ‘product’ as it is null. An error appears
ItemDetail.js
import React, { useState, useEffect } from "react";
import { useParams } from "react-router-dom";
import axios from "axios";
function ItemDetailPage() {
const { id} = useParams();
const [product, setProduct] = useState(null);
const { prodImageURL, name, funding, personnel, price } = product;
console.log("prodImageURL, name, funding, personnel, price",prodImageURL, name, funding, personnel, price);
const imgURL_full = `http://localhost:5001/${prodImageURL}`;
console.log("product", product);
useEffect(() => {
axios.get(`http://localhost:5001/products/${id}`)
.then((response) => {
setProduct(response.data);
})
.catch((error) => {
console.error(error);
});
}, [id]);
if (!product) {
return <div>삼품이 없습니다</div>;
}
return (
<div>
<div className='detail-info'>
<img src={imgURL_full} alt={name} />
<div className='detail-text'>
<p className='detail-title'>{name}</p>
<p className='detail-funding'>펀딩 진행중:{funding}</p>
<p className='detail-personnel'>펀딩 인원:{personnel}</p>
<p>가격: {price}</p>
</div>
</div>
</div>
);
}
export default ItemDetailPage;
2
Answers
The error is happening because you don’t have the
product
data while you are destructuring. You can fix this by moving the destructuring part below the return so that the code won’t be reached before product value is set. As:Please implement InitialValue: