Search code examples
reactjsreduxreact-reduxredux-thunk

Struggling to Get Array Data From Redux Store


I have not been able to access items in an array that I am retrieving with redux. When I do console logs in the action itself, I am able to access array elements individually. But once that data makes its way to the component for display following the dispatch of actions, I have been unable to parse the data structure without error.

ListingActions.js: If I do a console log here, I can parse through the different indices of the variable data without issue

export const getListings = () => async (dispatch) => {
try {
    dispatch({ type: LISTING_REQUEST })

    const { data } = await axios.get('/gmk')
    // I can access the elements of the array here without a problem

    dispatch({ type: LISTING_SUCCESS, payload: data })
} catch (error) {
    dispatch({
        type: LISTING_FAIL,
        payload: error.response && error.response.data.message ? error.response.data.message : error.message,
    })
}

ListingReducers.js:

export const listingReducer = (state = { itemListings: [] }, action) => {
switch (action.type) {
    case LISTING_REQUEST:
        return { loading: true, itemListings: [] }
    case LISTING_SUCCESS:
        return { loading: false, itemListings: action.payload }
    case LISTING_FAIL:
        return { loading: false, error: action.payload }
    default:
        return state
}

Snippet from store.js:

const initialState = {
itemListings: [],
nope: { nopeItems: nopeItemsFromStorage },
keep: { keepItems: keepItemsFromStorage },

HomeScreen.js:

function HomeScreen() {
const dispatch = useDispatch()

const freshItemListings = useSelector((state) => state.itemListings)
const { loading, error, itemListings } = freshItemListings

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

return <div>{loading ? <p>Loading</p> : error ? <p>{error}</p> : itemListings.length}</div>

You'll see that I am trying to just access the length of itemListings. When I do so, I get an error: TypeError: Cannot read properties of undefined (reading 'length'). I have done other things like itemListings[0], and other methods just to see what my options are, but each has resulted in an error.


Solution

  • I discovered that the issue was with properly setting up the initial state in my store. I did change some of the variable names as suggested to make readability easier as well.

    Changes to store.js:

    const initialState = {
    listingData: { itemListings: [], loading: true },
    nope: { nopeItems: nopeItemsFromStorage },
    keep: { keepItems: keepItemsFromStorage },
    

    Setting both the loading and itemListing portions to the proper initial state was ultimately the answer.