noderaider / localsync

Real-time browser state synchronization across multiple tabs.

Home Page:http://localsync.js.org

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Not working with React

gatlanticus opened this issue · comments

I want to use localsync in React to log user out of all tabs when they log out of one tab.

When the trigger is called, the action executes in one tab, but the handler is not called in another. Tested in Chrome. I have something like the following:

export class App extends Component {
  componentDidMount(){
    this.globalLogout = localsync('logout', this.syncAction, this.localLogout, {tracing: true});
  }

  syncAction = () => {/*do nothing*/ return;}

  localLogout = () => {console.log("user has been logged out of this tab");}

  logoutUser = () => {
    this.localLogout();
    this.globalLogout.trigger();
  }
}

In the console, I got storagesync#start on for each Chrome tab that I opened. I then got storagesync#trigger > [] on calling logoutUser in one tab, but nothing happens in the other tabs. I expected to get the message "user has been logged out of this tab" on every tab.

Are you not missing this.globalLogout.start() somewhere to start the synchronisation.

In addition to what @filipkis mentioned, I probably wouldn't recommend creating the synchronizer within componentDidMount unless there is a good reason to. The example here doesn't use props / state in its callback methods. If you need to create it inside a component I'd recommend swapping to:

export class App extends Component {
  globalLogout = localsync('logout', this.syncAction, this.localLogout, {tracing: true});

  componentDidMount() {
    this.globalLogout.start();
  }

  componentWillUnmount() {
    this.globalLogout.stop();
  }

  // etc.
}

Above is the v1 API. I just released a v2 rewritten in TypeScript with less dependencies (direct / transitive). Being TypeScript, there should be less chance of runtime bugs and uses will get rich type information. If either of you upgrade, it would be great to get feedback.

The new version has a similar but is curried:

import { localsync } from "localsync";

const logoutSync = localsync({ channel: "logout", level: "DEBUG" });
const logoutController = channelSync(<publisher>, <subscriber>);
logoutController.start();

v2 API still exports a default localsync export that acts as a shim to support the older API (deprecated). It is now recommended to use the named localsync export.

The level configuration property controls the log level (DEBUG, INFO, WARN, ERROR). It defaults to INFO in development and ERROR in production.

The shape of publisher and subscriber are identical to the action / handler from v1.

Thanks!