How to send an action from a service not suspecting about Redux?

Let's say I have a geolocation service that Redux does not know, and I configure it like this:

backgroundGeoLocation.configure( callback // will be called with an argument when the coordinates change ); 

What is the cleanest way to make a callback service callback Redux without exporting the store from a separate module and using store.dispatch() (because it will be plain)?

+5
source share
2 answers

If you want to pass some value to some piece of code in JavaScript, you need to use functions.
For instance,

 function createGeoLocationService(store) { let backgroundGeoLocation = new BackgroundGeoLocation() backgroundGeoLocation.configure(coordinates => { store.dispatch({ type: 'UPDATE_COORDINATES', coordinates }) }) return backgroundGeoLocation } 

Now, wherever you create the repository, create this service:

 let store = createStore(reducer) let backgroundGeoLocation = createGeoLocationService(store) 

If you need to access them in components, you can:

  • Make a singleton (yes, not what you wanted, but its a valid option for client applications)
  • Skip it explicitly through the details (it can become tedious, but the most simple and clear)
  • Pass it implicitly through the context (very simple, but you will be dealing with an unstable API that can be changed , so its up to you)
+10
source

If you do not want callbackFn know about store.dispatch , you should create something like an event stream or Observable with callbackFn . And once you have done this, just map the stream to the store.dispatch function.

You can use any lib to create threads, but I recommend Rx

In this approach, you should come up with something like:

 var geoLocation$ = new Rx.Subject(); var newCoordinatesAction = coordinates => ({ type: "YOUR_TUPE", payload: coordinates }); geoLocation$.map(newCoordinatesAction).map(store.dispatch); backgroundGeoLocation.configure(::geoLocation$.onNext); 
+1
source

Source: https://habr.com/ru/post/1243076/


All Articles