Beginner redux, how to deal with this problem?


import React from "react"
import ReactDOM from "react-dom";

import { createStore, applyMiddleware, compose, combineReducers } from "redux"
import { Provider } from "react-redux"

import App from "./modules/App"

const initialState = {
    cart: [
        {
            product: "bread 700g",
            quantity: 2,
            unitCost: 90
        },
        {
            product: "milk 500ml",
            quantity: 1,
            unitCost: 47
        }
    ]
}

const cartReducer = function(state=initialState, action) {
    return state;
}

const productsReducer = function(state=[], action) {
    return state;
}

const ADD_TO_CART = "ADD_TO_CART";

const cartReducer = function(state=initialState, action) {
    switch (action.type) {
        case ADD_TO_CART: {
            return {
                ...state,
                cart: [...state.cart, action.payload]
            }
        }

        default:
            return state;
    }
}

function addToCart(product, quantity, unitCost) {
    return {
        type: ADD_TO_CART,
        payload: {
            product,
            quantity,
            unitCost
        }
    }
}

const allReducers = {
    products: productsReducer,
    shoppingCart: cartReducer
}

const rootReducer = combineReducers(allReducers);

let store = createStore(rootReducer);

console.log("initial state: ", store.getState());

const element = document.getElementById("taskRouter");

store.dispatch(addToCart("Coffee 500gm", 1, 250));

ReactDOM.render(
    <div>
        <App />
    </div>,
    element
);

Apr.05,2021

this obvious error tip . The cartReducer method has been repeatedly defined.


constant cartReducer has been declared twice. You can just delete the previous declaration

.
// 
const cartReducer = function(state=initialState, action) {
    return state;
}

const declares that the constant cannot be repeated. The constant cartReducer declared twice

Menu