TypeError: state.products.find is not a function or its return value is not iterable

Viewed 18
import { ActionType } from "../costants/action-type";

const initialState = {
    products : [],
}


export const productReducer = (state = initialState, {type,payload}) => {

    console.log("DEC",payload)
    console.log("state",state.products)

    switch (type) {
        case ActionType.SET_PRODUCTS:
            return {state , 
                products: [...state.products.find(product => product.API === payload.API)],
            };
            default:
                return state;
            }
        }

The screenshot for my error

1 Answers

You should use map (returns a list) instead of find (returns a single object).

And you should assign state like {...state } to keep all current state values as well.

import { ActionType } from "../costants/action-type";

const initialState = {
    products : [],
}


export const productReducer = (state = initialState, {type,payload}) => {

    console.log("DEC",payload)
    console.log("state",state.products)

    switch (type) {
        case ActionType.SET_PRODUCTS:
            return {
                ...state, 
                products: [...state.products.map(product => product.API === payload.API)],
            };
            default:
                return state;
            }
        }

Related