Miguel Pinto
Miguel Pinto

Reputation: 497

React Native - Redux

So, im getting started with react native and redux. I'm trying to setup a basic app state, just a counter property to increment when a button is pressed. Basically, no error is thrown but the state doesnt get updated, at least in the screen the counter keeps having the same value.

Ill try to document the code bellow.

App.js - its where I create the store and a basic reducer

import {createStore} from 'redux'
import {Provider} from 'react-redux'

import App from './src/App'

const initialState = { counter: 0 }
const reducer = (state=initialState, action) {
  switch(action.type)
  {
     case 'INCREASE_COUNTER':
       return {counter: state.counter++}
  }
  return state;
}
const store = createStore(reducer)

class AppProvider extends React.Component {
  render() {
     return (
        <Provider store={store}>
           <App />
        </Provider>
     )
  }
}

export default AppProvider

./src/App.js - its where i have the View implemented

import {connect} from 'react-redux';

class App extends React.Component  {
   render() {
      return (
         <View>
           <Button title="increase" onPress={this.props.increaseCounter}/>
           <Text>Counter: {this.props.counter}</Text>
         </View>
      )
   }
}

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

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

export default connect(mapStateToProps)(App);

So no error is thrown but the screen still shows Counter: 0 as I press the button. I'm probably missing something here.

Any help would be awesome. Thanks and happy programming!

Upvotes: 0

Views: 35

Answers (1)

Pooya Haratian
Pooya Haratian

Reputation: 785

I guess you should pass mapDispatchToProps to connect function.

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

https://react-redux.js.org/api/connect

Upvotes: 1

Related Questions