1

I have tried many different ways to implement shared worker fibWorkerShared.js , but so far none of them works.

First try:

onconnect = (e) => {
  var port = e.ports[0];

  port.postMessage("I'm alive!");

  port.onmessage = function (e) {
    port.postMessage("I'm good!");
  };
};

Result: React compile error
ERROR in src\fibWorkerShared.js Line 1:1: 'onconnect' is not defined no-undef

Second try:

export default () => {
  self.addEventListener("connect", (e) => {
    var port = e.ports[0];
    console.log("message received", e);

    port.start();

    port.postMessage("I'm alive!");
  });
};

Result: React compile error
ERROR in src\fibWorkerShared.js Line 4:3: Unexpected use of 'self' no-restricted-globals

Third try:

export default () => {
  addEventListener("connect", (e) => {
    var port = e.ports[0];
    console.log("message received", e);

    port.start();

    port.postMessage("I'm alive!");
  });
};

Result: React compile error.
ERROR in src\fibWorkerShared.js Line 4:3: Unexpected use of 'addEventListener' no-restricted-globals

Forth try:

function onconnect(e) {
  var port = e.ports[0];

  port.postMessage("I'm alive!");

  port.onmessage = function (e) {
    port.postMessage("I'm good!");
  };
}

Result: no compile error, but the worker did not receive nor respond any message. I guess the function onconnect is no longer the event connect listener.

The code snippet that initiates shared worker is following (I use almost same code except Worker instead of SharedWorker for initiating dedicated worker which works fine):

 useEffect(() => {
    console.log("useEffect [] for shared Worker");

    if (!sharedWorker) {
      sharedWorker = new SharedWorker(
        new URL("./fibWorkerShared.js", import.meta.url)
      );

      sharedWorker.port.postMessage("Hello worker!");

      sharedWorker.port.onmessage = function (e) {
        console.log("First app", "<<<", e.data);
      };
    }
  }, []);

Search Google several hours, no working example for react v18 found.

Godmin Bao
  • 11
  • 1

1 Answers1

0

You can inspect workers here: chrome://inspect/#workers In my case there was an type error further down the code which resulted in none of the logs before that line to print See this answer: https://stackoverflow.com/a/31079750/12234839

curley633
  • 3
  • 2