Estou tentando renderizar alguns produtos vindos da minha api, porém recebo este erro: TypeError: Cannot read property 'map' of undefined
Segue o código da 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 });
}
};
Código do reducer:
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;
}
};
E por fim, código da página que será renderizada:
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>
</>
)
}