Possible to dispatch an action without connect?

Viewed 10991
export default class App extends Component {
...
  componentDidMount() {
    //registering event listener
    BackgroundGeolocation.on('location', this.onLocation, this.onError);
  }

  onLocation(location) {
   //wishing to dispatch an action to update variable in store
  }

  render() {
    return (
      <Provider store={store}>
        <AlertProvider>
          <MainNavigator screenProps={{ isConnected: this.state.isConnected }} />
        </AlertProvider>
      </Provider>
    );
  }
}

From what I understand, I can't possibly connect to store in this component as we are just configuring and pass the store into Provider. How would i possibly dispatch an action in my onLocation event?

4 Answers

You can directly dispatch using the store object.

store.dispatch({type:"UPDATE_VARIABLE", payload:variable.value})

If you are in some other component where the store object isnt readily available, export it from the main component and import it to a location where it is needed and use the above statement

react-redux has own hooks to call them

const dispatch = useDispatch();
const state = useSelector((state) => state);

do not forget to import them

import { useDispatch, useSelector } from 'react-redux';

vs code will autocomplete if you write useDispatch

You can use this code and add the constructor in the class like this

  constructor(props) {
    super(props);
  }

  onLocation() {
    this.props.dispatch({type: GET_THINGS_REQUESTED, payload: value});
  }

UmiJS 3.x users can do:

import { getDvaApp } from 'umi';

const dispatch = getDvaApp()._store.dispatch;

dispatch({ … })
Related