'Redux action gives an array with undefined key

In my react component I have sucessfuly created as state the json data from my api and I can use it as an array. However I can't access individual object keys inside that array, whenever I try to use it it gives an undefined error. If I console.log(products) the app works fine, but when I try console.log for example (products[0].name) it logs, but right after it gives Uncaught TypeError: Cannot read properties of undefined (reading 'name') and the app breaks down.

React code

import React, { useEffect } from "react";
import {useDispatch, useSelector} from 'react-redux'
import { listPoduct } from "../actions/productActions";

const Examples = () => {

    const dispatch = useDispatch()

    const productList = useSelector(state => state.productList)
    const {loading, error, products} = productList

    useEffect(()=>{
        dispatch(listPoduct())
    },[dispatch])

    console.log(products[0].name)

    return(
        <div>
          ...
        </div>
    )
}

export default Examples

Store

import {createStore, combineReducers, applyMiddleware} from 'redux' 
import thunk from 'redux-thunk'
import {composeWithDevTools} from 'redux-devtools-extension' 
import {productListReducer} from './reducers/productReducer'

const reducer = combineReducers({
    productList: productListReducer,
})

const initialState = {}

const middleware = [thunk]

const store = createStore(
    reducer,
    initialState,
    composeWithDevTools(applyMiddleware(...middleware))
  )

export default store 

Reducer

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}
        case PRODUCT_LIST_FAIL:
            return {loading:false, error: action.payload}
        default:
            return state
    }
}

Action

import axios from 'axios'
import {
    PRODUCT_LIST_REQUEST,
    PRODUCT_LIST_SUCCESS,
    PRODUCT_LIST_FAIL
} from '../constants/productConstants'

export const listPoduct = () => async(dispatch) => {
    try {
        dispatch({type:PRODUCT_LIST_REQUEST})

        const {data} = await axios.get('/api/images')

        dispatch({
            type:PRODUCT_LIST_SUCCESS,
            payload:data
        })
    } catch(error) {
        dispatch({
            type:PRODUCT_LIST_FAIL, 
            payload:error.response 
        })
    }
}


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source