I'm building a React app and am calling a custom handler library to make calls to our REST API.
Within these (non-React) functions, I'd like to trigger Redux actions to update the store with the endpoint response, but can't figure out how to trigger the Redux action without the usual 'mapDispatchToProps'/connect() method.
Is this possible?
Thanks
If you need to dispatch actions from outside a React component, the same technique will work: import the store, then call store. dispatch() , passing the action you need to dispatch. It works the same as the dispatch function you get from props via react-redux's connect function.
using useDispatch outside of a component will cause errors.
You just need to export the store from the module where it created with createStore() . Also, it shouldn't pollute the global window object.
In order to dispatch and action from outside of the scope of React.Component
you need to get the store instance and call dispatch
on it like
import { store } from '/path/to/createdStore'; function testAction(text) { return { type: 'TEST_ACTION', text } } store.dispatch(testAction('StackOverflow'));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With