Search code examples
javascriptreactjsreduxreact-redux

TypeError: Cannot read properties of undefined (reading 'numberOfCakes')


I am beginner to React and Redux I am trying to learn Redux with React. I have created a store in store.js as below -

const redux = require("redux");
const createStore = redux.createStore;

const BUY_CAKE = "BUY_CAKE";

function buyCake() {
  return {
    type: BUY_CAKE,
  };
}

const initialState = {
  numberOfCakes: 25,
};

const cakeReducer = (state = initialState, action) => {
  switch (action.type) {
    case BUY_CAKE:
      return {
        ...state,
        numberOfCakes: state.numberOfCakes - 1,
      };
  }
};

const store = createStore(cakeReducer);

store.subscribe(() => {
  console.log("updated State: ", store.getState());
});

// store.dispatch(buyCake());

export { buyCake, store };

And my component is like this -

import * as React from "react";
import { Component } from "react";
import { connect } from "react-redux";
import { buyCake } from "./redux/store";

class CakeContainer extends Component {

  constructor(props) {
    super(props);
  }

  render() {
      console.log("props: ", this.props);
    return (
      <div>
        <h2>No of cakes = {this.props.numberOfCakes}</h2>
        <button>Buy Cake</button>
      </div>
    );
  }
}

// take redux state -> retruns an object
const mapStateToProps = (state) => {
  return {
    numberOfCakes: state.numberOfCakes,
  };
};

const mapDispatchToProps = (dispatch) => {
  return {
    buyCake: () => dispatch(buyCake()),
  };
};


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

`

The problem I am facing is that, when I am not using dispatch() at least once in the store.js file, I am getting this error - TypeError: Cannot read properties of undefined (reading 'numberOfCakes') See Error Here

If I use dispatch() at least once in store.js file, then this error goes away. Error Vanished after dispatch

Can anyone please tell why is this happening ??


Solution

  • this error because you forgot to add the default case in reducer the code will like this.

    switch (actions.type) {
        case BUY_CAKE_TYPE:
          return {
            numberOfCake: state.numberOfCake - 1,
          };
        default:
          return state;
      }