58

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

TUrwin
  • 755
  • 1
  • 5
  • 9

2 Answers2

146

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'));
Nickofthyme
  • 3,032
  • 23
  • 40
Shubham Khatri
  • 270,417
  • 55
  • 406
  • 400
-2

I really love to copy the resolve/reject or onSuccess/onError pattern used by Promise.

So I suggest you to do the same thing. You call the custom handler and pass it an onSuccess and an onError callbacks. So when you fetch data you can call onSuccess and in case of error you can call the onError callback.

onSuccess and onError are functions that you will have in your component which will show to the user something or will do other stuff (show an error toast message in case of error ?!).

Let see an example:

export default class CustomService{
    getData(onSuccess, onError){
        //axios.get(...) or fetch(...)
        if(success) call onSuccess(result)
        if(error) call onError(error)
    }
}

export default class MyComponent extends React.Component{
   constructor(props){
       super(props);

       this.state = {
           showError:false
       }

       this.customService = new CustomService();

       this.onSuccess = this.onSuccess.bind(this);
       this.onError = this.onError.bind(this);
   }

   componentDidMount(){
       this.customService.getData(this.onSuccess, this.onError);
   }

   onSuccess(result){
       // Do something if necessary
       // Call the redux action
   }

   onError(error){
       //Show a toast message to user or do something else
       this.setState({showError:true});
   }
}

Inside the onSuccess you can call Redux to store your data.

Paolo Dell'Aguzzo
  • 1,431
  • 11
  • 14