0
I am trying to render some products coming from my api, however I get this error: Typeerror: Cannot read Property 'map' of Undefined
Follow the code of the action:
export const listProducts = () => async (dispatch) => {
dispatch({
type: PRODUCT_LIST_REQUEST,
});
try {
const { data } = await axios.get('/api/products');
dispatch({ type: PRODUCT_LIST_SUCCESS, payload: data });
} catch (error) {
dispatch({ type: PRODUCT_LIST_FAIL, payload: error.message });
}
};
Code of the Sovereign:
export const productListReducer = (state = { loading: true, products: [] }, action) => {
switch (action.type) {
case PRODUCT_LIST_REQUEST:
return { loading: true };
case PRODUCT_LIST_SUCCESS:
return {
loading: false,
products: action.payload.products,
};
case PRODUCT_LIST_FAIL:
return { loading: false, error: action.payload };
default:
return state;
}
};
And finally, page code that will be rendered:
import React, { useState, useEffect } from 'react';
import { Link } from 'react-router-dom';
import { useDispatch, useSelector } from 'react-redux';
import { listProducts } from '../../../actions/productActions';
import './style.css';
export default function PageProducts() {
const dispatch = useDispatch();
const productList = useSelector((state) => state.productList);
const { products } = productList;
useEffect(() => {
dispatch(listProducts());
}, [dispatch]);
return (
<>
<section className="card-last-prod">
<h2>Últimos produtos</h2>
<div className="card-last-pro-grid">
{products.map((product) => (
<div key={product._id} className="card-last-prod-item">
<Link to="/">
<div className="card-last-prod-item-img">
<img src={product.img} alt="" />
</div>
<div className="btn">
<button> Detalhes</button>
</div>
<p>{product.name}</p>
</Link>
</div>
))}
</div>
</section>
</>
)
}
I did what I said, I still have the same bug. I already checked the path in Axios, I’ve already made authentication requests as well and everything is ok.. including product requisition works normally in India, I don’t know what that could be.
– Regex
How is the return of the api?
– Hiogo Cavalheiro