Search code examples
javascriptreactjsreduxreact-redux

react-redux Cannot read properties of undefined


In this Code, I use react-redux and react-router. the react-redux version is old but I want to know where I went wrong in this piece of code (in this version of react-redux and react-router I meant). I try to get ingredients in main.jsx and use it in OrderSummary Component but I got errors like:

  • Cannot read properties of undefined,
  • state not found.

github repository

main.jsx:

import ReactDOM from "react-dom/client";
import { BrowserRouter, Routes, Route } from "react-router-dom";
import { Provider } from "react-redux";
import { createStore } from "redux";
import reducer from "./store/reducer";

export default function Main(props) {
  const store = createStore(
    reducer /* preloadedState, */,
    window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__()
  );

  return (
    <Provider store={store}>
      <BrowserRouter>
        <Routes>
          <Route path="/" element={<Layout />}>
            <Route index element={<App />} />
            <Route
              path="/burger-builder/order-page"
              exact
              element={
                <OrderSummary
                  ingredients={props.ingredients}
                  totalPrice={props.totalPrice}
                />
              }
            />
            <Route path="*" element={<NoPage />} />
          </Route>
        </Routes>
      </BrowserRouter>
    </Provider>
  );
}

const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(<Main />);

BurgerBuilder.jsx:

import * as actionTypes from "../../store/action";
import { connect } from "react-redux";

function BurgerBuilder(props) {
return (
    <>
      <Burger ingredients={props.ings} />
      <BurgerControls
        addIngredients={props.onIngredientAdded}
        removeIngredients={props.onIngredientRemoved}
        totalprice={props.totalPrice}
        disabled={disableButton}
      />
    </>
  );
}

const mapStateToProps = (state) => {
  return {
    ings: state.ingredients,
    price: state.totalPrice,
  };
};

const mapDispatchToProps = (dispatch) => {
  return {
    onIngredientAdded: (ingName) =>
      dispatch({ type: actionTypes.ADD_INGREDIENT, ingredientName: ingName }),
    onIngredientRemoved: (ingName) =>
      dispatch({
        type: actionTypes.REMOVE_INGREDIENT,
        ingredientName: ingName,
      }),
  };
};

export default connect(mapStateToProps, mapDispatchToProps)(BurgerBuilder);

part of

reducer.js:

const reducer = (state = initialState, action) => {
    switch (action.type) {
        case actionTypes.ADD_INGREDIENT:
            return {
                ...state,
                ingredients: {
                    ...state.ingredients,
                    [action.ingredienName]: state.ingredients[action.ingredientName] + 1
                },
                totalPrice: state.totalPrice + INGREDIENT_PRICES[action.ingredientName]
            };

Solution

  • In your Main component, you're passing props.ingredients and props.totalPrice to OrderSummary, but props is not defined in Main -- you don't pass any when you render Main with root.render(<Main />);.

    To get around this, you can connect OrderStatus to the Redux store like you do with BurgerBuilder:

    
    function OrderSummary(props) {
        // access mapped props
        const { ingredients, totalPrice } = props;
    
        // ...
    };
    
    const mapStateToProps = (state) => {
        return {
            ingredients: state.ingredients,
            totalPrice: state.totalPrice,
        };
    };
    
    export default connect(mapStateToProps)(OrderSummary);
    

    Then, in Main, render OrderSummary without props:

    <Route path="/burger-builder/order-page" exact element={<OrderSummary />} />
    

    Also, there's a typo in your reducer. You wrote action.ingredienName instead of action.ingredientName in the ADD_INGREDIENT case. Here's the fixed reducer.js:

    case actionTypes.ADD_INGREDIENT:
        return {
            ...state,
            ingredients: {
                ...state.ingredients,
                [action.ingredientName]: state.ingredients[action.ingredientName] + 1
            },
            totalPrice: state.totalPrice + INGREDIENT_PRICES[action.ingredientName]
        };