DEV Community

Cover image for ShareService: a library for building multiple tabs react app
Embbnux Ji
Embbnux Ji

Posted on

ShareService: a library for building multiple tabs react app

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

howitwork

SharedWorker instance will be reused by cross browser tabs with same domain until all pages are closed.

  1. App creates SharedWorker to load data generate UI state when user open first tab.
  2. App gets UI state from existing SharedWorker instance when user load second tab.
  3. App send action to execute in SharedWorker instance when user has action in web page
  4. 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
Enter fullscreen mode Exit fullscreen mode

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:

  1. Add support for Vue.js library.
  2. Support Browser extension (with background API)
  3. Support Electron main and render process

To make Browser extension and Electron app support the centralization service.

Original link

Top comments (0)