Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dispatching redux actions inside custom serviceWorker

I want to perform actions on push received from server. I have a custom service worker which has the event listener for push. Now i want to dispatch redux actions when i recieve the push from server. My custom service worker lives inside public folder at the moment. And i am unable to import the store inside this file. Any help would be highly appreciated. Thanks!

like image 596
Harshit Agarwal Avatar asked Mar 04 '23 13:03

Harshit Agarwal


1 Answers

It is not possible to dispatch Redux actions inside your Service Worker code.

However, what you actually want to do, is communicate using the postMessage API. Using postMessage, you can send the browser JS context a message when the SW receives a push from the server. You can find more info eg. here https://developer.mozilla.org/en-US/docs/Web/API/Client/postMessage.

Why is it like this? This is a consequence of the different execution contexts. Your normal JS code (React, Redux, actions etc.) run in the browser context where as your Service Code runs in the SW context. Those two contexes don't share ANY variables or state. For that reason, you cannot call any functions (eg. Redux actions) inside your SW code. You need to communicate between the two contexes and then, upon receiving a message in the browser context, call whatever functions you wish.

like image 133
pate Avatar answered Mar 23 '23 00:03

pate