Accessing redux store / functions from Navigation.js inside a tabBar

Viewed 24

I'm struggling a bit accessing some redux functions from Navigation.js. I want to be able to call a redux function when I press a tab on a tabBar. To do this, I am calling

Navigation.js:

tabBarOnPress: () => {
 console.warn("I am here")
store.dispatch({ type: nameOfMyReduxFunction, })}

I correspondingly have, in a separate reducer / redux file:

export const nameOfMyReduxFunction = () => {
    console.warn("nameOfMyReduxFunction being called")
    return dispatch => {
        dispatch({ type: "NAME_OF_MY_REDUX_FUNCTION" });
    };
};

When I run the app, I get "I am here". However, the redux function appears to never run, as "nameOfMyReduxFunction being called" is never printed. Could anyone give me some tips on why this is?

1 Answers

You can use connect from react-redux package.

So first, we import the nameOfMyReduxFunction from that file and dispatch it from a function (which is named here as mapDispatchToProps).

While exporting the component we use the connect to connect the mapDispatchToProps function with the component like export default connect(null, mapDispatchToProps)(Navigation.js).

You can call the nameOfMyReduxFunction within the component from prop like props.nameOfMyReduxFunction.

import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import { nameOfMyReduxFunction } from 'thatReduxFile';
...

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

...

tabBarOnPress: () => {
 console.warn("I am here")
 store.dispatch({ type: props.nameOfMyReduxFunction, })  //Access nameOfMyReduxFunction from props
}  

...

export default connect(null, mapDispatchToProps)(Navigation.js)

For more info refer connect, mapDispatchToProps. bindactioncreators

Related