DEV Community

Ahmed Mohamed
Ahmed Mohamed

Posted on

ProductDetails.jsx:55 Uncaught TypeError: Cannot read properties of undefined (reading 'name')

I have got this error when I am trying to get product details from api.
ProductDetails.js :

``import { useParams } from "react-router-dom";
import styles from "./ProductDetails.module.css";
import { useEffect } from "react";

import { useDispatch, useSelector } from "react-redux";
import { detailsProduct } from "../../Redux/actions/productActions";
import Loading from "../../components/Loading/Loading";
import MessageBox from "../../components/MessageBox/MessageBox";

function ProductDetails() {
const dispatch = useDispatch();
const { productId } = useParams();
const { product, error, loading } = useSelector(
(state) => state.productDetails
);

useEffect(() => {
dispatch(detailsProduct(productId));
}, [dispatch, productId]);

return (
<>


{product.name}

    {loading ? (
      <Loading />
    ) : error ? (
      <MessageBox>{error}</MessageBox>
    ) : (
      <h2>{product.name}</h2>
    )}
  </div>
</>

);
}
`
export default ProductDetails;

productAction.js :


export const detailsProduct = (productId) => async (dispatch) => {
dispatch({ type: PRODUCT_DETAILS_REQUEST, payload: productId, });
try {
const { data } = await Axios.get(
/api/products/${productId});
dispatch({type: PRODUCT_DETAILS_SUCCESS,payload: data});
} catch (error) {
dispatch({
type: PRODUCT_DETAILS_FAIL,
payload:
error.response && error.response.data.message
? error.response.data.message
: error.message,
});
}
};

productReducer.js :

`
export const productDetailsReducer = (
state = { loading: true, product: {} }, action) => {
switch (action.type) {
case PRODUCT_DETAILS_REQUEST:
return { loading: true };

case PRODUCT_DETAILS_SUCCESS:
  return { loading: false, product: action.payload };
case PRODUCT_DETAILS_FAIL:
  return { loading: false, error: action.payload };

default:
  return state;

}
};
`

Top comments (0)