1

'action' is not defined in Redux

I try to create a reducer for web store cart component, but I've come across this error:

'action' is not defined

My code is as follows:

 import { CART_ADD_ITEM } from "../constants/cartConstants";
 import { addToCart } from '../actions/cartActions';
 export const cartReducer = (state = { cartItems: [], action }) => {
switch(action.type){
    case CART_ADD_ITEM:
        const item = action.payload;
        //we check if the item exists in state
        const existItem = state.cartItems.find(x => x.product === item.product);
        
        if(existItem){
            return {
                ...state,
                cartItems: state.cartItems.map(x => x.product === existItem.product ? item : x),
            }
        } else {
            return {
                ...state,
                cartItems : [...state.cartItems, item],
            }
        }
    default:
        return state;
}
 };

This is what cartActions looks like. It seems that it has to be somehow used by the previous code, but how? import axios from 'axios'; import { CART_ADD_ITEM } from '../constants/cartConstants';

export const addToCart = (id, quantity) => async(dispatch, getState) => { const {data} = await axios.get(/api/products/${id});

dispatch({
    type: CART_ADD_ITEM,
    payload: {
        product: data._id,
        name: data.name,
        image: data.image,
        price: data.price,
        countInStock: data.countInStock,
        quantity,
    }
});
//once dispatched, we wnt ot save an item to local storage added to cart to local storage
//we get it in store.js 
localStorage.setItem('cartItems', JSON.stringify(getState().cart.cartItems));
 }

What is wrong with this?

Submitted May 22nd 2021 by Admin

Answers
0

Your reducer expects an action as the second argument. Right now, your code includes action as a property in the default state, which is incorrect. The reducer type signature should likely be like this:

export const cartReducer = (state = { cartItems: [] }, action) => { // Reducer content here
}

Admin | 3 months ago


0

The reducer takes the initial state as the first argument and action as the second.

Improved

let initialState = {cartItems: []}
export const cartReducer = (state = initialState, action) => {
switch(action.type){ case CART_ADD_ITEM: //we check if the item exists in state const existItem = state.cartItems.find(x => x.product === action.payload.product); if(existItem){ return { ...state, cartItems: state.cartItems.map(x => x.product === existItem.product ? action.payload : x), } } else { return { ...state, cartItems : [...state.cartItems, action.payload], } } default: return state;
} };

Admin | 3 months ago



Relevant Questions




Deleting a todo - MERN Stack

September 10th 2021