I am trying to receive the GET API result data to the component using redux-reducers and actions, component is not able to receive the data, it is showing below error in the component.
NOTE: I can able to see the result data in redux-actions file, but same data is not going to component
ERROR
HomeScreen.js:17 Uncaught TypeError: Cannot read properties of undefined (reading 'map')
at HomeScreen (HomeScreen.js:17:1)
REDUCER FILE
import { PRODUCT_LIST_REQUEST,
PRODUCT_LIST_SUCCESS,
PRODUCT_LIST_FAIL
} from '../constants/productConstants'
export const productListReducer = (state = { products: [] }, action) => {
switch (action.type) {
case PRODUCT_LIST_REQUEST:
return { loading: true, products: [] }
case PRODUCT_LIST_SUCCESS:
return {
loading: false,
products: action.payload.products,
}
case PRODUCT_LIST_FAIL:
return { loading: false, error: action.payload }
default:
return state
}
}
ACTION FILE
import axios from 'axios'
import { PRODUCT_LIST_REQUEST,
PRODUCT_LIST_SUCCESS,
PRODUCT_LIST_FAIL
} from '../constants/productConstants'
export const listProducts=()=> async(dispatch)=>{
try{
dispatch({type:PRODUCT_LIST_REQUEST})
const {data}= await axios.get('/api/products/')
console.log("data-------------")
console.log({data})
dispatch({
type:PRODUCT_LIST_SUCCESS,
payload:data
})
}catch(error){
dispatch({
type:PRODUCT_LIST_FAIL,
payload:error.response && error.response.data.detail
? error.response.data.detail
:error.message
})
}
}
COMPONENT FILE
import React ,{useState, useEffect} from 'react'
import {Row,Col} from 'react-bootstrap'
import ProductList from '../components/ProductList'
import {useDispatch, useSelector } from 'react-redux'
import { listProducts } from '../actions/productActions'
export default function HomeScreen() {
const dispatch = useDispatch()
const productList = useSelector(state => state.productList)
const { error, loading, products, page, pages } = productList
useEffect(() => {
dispatch(listProducts())
}, [])
return (
<div>
<Row>
{products.map(product => (
<Col key={product._id} sm={12} md={6} lg={4} xl={3}>
<ProductList product_details={product}></ProductList>
</Col>
))}
</Row>
</div>
)
}