Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to trigger a Redux action from outside a component? [duplicate]

Tags:

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

like image 721
TUrwin Avatar asked Jun 21 '18 07:06

TUrwin


People also ask

Is it possible to trigger a Redux action from outside a component?

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.

Can you use useDispatch outside of component?

using useDispatch outside of a component will cause errors.

How do I access Redux store outside a component?

You just need to export the store from the module where it created with createStore() . Also, it shouldn't pollute the global window object.


1 Answers

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')); 
like image 180
Shubham Khatri Avatar answered Sep 20 '22 09:09

Shubham Khatri