ref: https://github.com/JuniorChang/SojuSushi/blob/main/frontend/src/screens/ProductScreen.js
in my code line 155-200, the page will not show anything when I first come to the page. However if i comment off these lines, the rest of the page appears, I proceed to uncomment these lines, it now appears correctly. Again, if I refresh the page, it goes blank again. the console is showing : Uncaught TypeError: Cannot read properties of undefined (reading 'map')
CodePudding user response:
use && or ?.
{productDetails?.product?.reviews?.length === 0 && <Message>No Reviews</Message>}
<ListGroup variant='flush'>
{productDetails?.product?.reviews?.map((review) => (
<ListGroupItem key={review._id}>
<strong>{review.name}</strong>
<Rating value={review.rating} />
<p>{review.createdAt.substr(0,10)}</p>
<p>{review.comment}</p>
</ListGroupItem>
))}
reviews. length only gives the length of the array.
CodePudding user response:
Uncaught TypeError: Cannot read properties of undefined (reading 'map')
this is a super generic error message. Your variable is undefined, and you are accessing map.
The reason for this is likely
dispatch(listProductDetails(id));
dispatch({ type: PRODUCT_CREATE_REVIEW_RESET });
Essentially the state go from
- REQUEST:: productList=null, loading=true, error=null
- RESET:: productList=null, loading=null, error=null
- SUCCESS:: productList=(object), loading=true, error=null
On the RESET render, it will attempt to access the object without be initialized
You can use the redux plugin in chrome to see your actions and how they are affecting your store. Its a great plugin
CodePudding user response:
An advice for the next time you ask a question, try to break down more on the issue you are dealing with.
That being said, after i read your code, i think you should use the ?
operator when calling a array
method from an array
that could be undefined
like this:
array?.map(...)
or u just do this instead:
array.length > 0 && array.map