Search code examples
react-nativereduxreact-reduxstate-management

React Native & Redux : undefined is not an object (evaluating 'state.counter')


I was trying to use Redux in my React Native project to create a counter app. But then I encounter this error. It says sth like undefined is not an object (evaluating 'state.counter')

Please have a look at my code.

Counter.js

class Counter extends Component {
  state = {counter: 0};

  render() {
    return (
      <View style={styles.container}>
        <View style={styles.counterPart}>
          <TouchableOpacity onPress={() => this.props.increaseCounter()}>
            <Text style={styles.text}>Increase</Text>
          </TouchableOpacity>
          <Text style={styles.text}>{this.props.counter}</Text>
          <TouchableOpacity onPress={() => this.props.decreaseCounter()}>
            <Text style={styles.text}>Decrease</Text>
          </TouchableOpacity>
        </View>
      </View>
    );
  }
}

function mapStateToProps(state) {
  return {
    counter: state.counter,
  };
}

function mapDispatchToProps(dispatch) {
  return {
    increaseCounter: () => dispatch({type: 'INCREASE_COUNTER'}),
    decreaseCounter: () => dispatch({type: 'DECREASE_COUNTER'}),
  };
}

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

The error seems to result from mapStateToProps(state) function above.

App.js

const reducer = (state = initialState, action) => {
  switch (action.type) {
    case 'INCREASE_COUNTER':
      console.log('Enter INCREASE_COUNTER reducer');
      return {counter: state.counter + 1};
    case 'DECREASE_COUNTER':
      console.log('Enter DECREASE_COUNTER reducer');
      return {counter: state.counter - 1};
  }
  return state;
};

const store = createStore(reducer);

const initialState = {
  counter: 0,
};

class App extends Component {
  render() {
    return (
      <Provider store={store}>
        <Counter />
      </Provider>
    );
  }
}

I would appreciate if you can provide a solution or a suggestion to this issue. Thank you.


Solution

  • I think the problem is that you can't access to initialState in reducer, try to move declaration on the top of reducer like so.

    const initialState = {
      counter: 0,
    };
    
    const reducer = (state = initialState, action) => {
      switch (action.type) {
        ...
      }
    }