We can use React to create single page apps easily, React helps us to render UI state. But for every new tab, app need to run our business logics and services to have data for react to rendering. So can we centralize our business logics and services?
SharedWorker
is the solution. And we have shared-service library to help you centralize your business logics and services and build a multiple tabs react app without pain.
How it work
SharedWorker instance will be reused by cross browser tabs with same domain until all pages are closed.
- App creates SharedWorker to load data generate UI state when user open first tab.
- App gets UI state from existing SharedWorker instance when user load second tab.
- App send action to execute in SharedWorker instance when user has action in web page
- SharedWorker instance send UI state to tabs that use it after action executing
Work with ShareService library
I assume you have start a react app with create-react-app
.
1 . First step: install it
$ npm install @shared-service/core @shared-service/react
2 . Init shared service in your react app root endpoint:
3 . Connect Shared Service in ShareWorker worker.js file:
4 . In react component:
For simple state logic, we can just use setCount
function return useSharedState
to update it into SharedService
.
For complex actions, we can send it to execute in sharedServiceServer
.
Firstly register executor into sharedServiceServer
at worker.js
:
Send the action in react component:
5 . Data persistence
We can persist data in SharedWorker with IndexedDB. Here we use localforage
lib to help us handle storage.
Online demo
We have online demo here. For full demo source code, please refer here.
Problem
As SharedWorker is not supported for Safari and IE now, so we canβt run share-service
at the shared worker for those Browser. You can take a look at here to make app work at Safari.
More
There are some TODO for shared-service
library:
- Add support for
Vue.js
library. - Support Browser extension (with background API)
- Support Electron main and render process
To make Browser extension and Electron app support the centralization service.
Original link
Top comments (0)