Search code examples
javascriptreactjsreact-reduxweb-worker

why I am not create object in useEffect in hooks?


I am trying to use webworker in our demo application, but I am not able to create instance of my worker. I get the error worker` is read only. Why?

Here is my code

https://codesandbox.io/s/bold-forest-s3guc?file=/src/App.js

import React, { useEffect } from "react";
import "./styles.css";
import worker from "./workerfile";
import WebWorker from "./setup";
export default function App() {
  const buttonHan = () => {
    alert("==g=");
  };

  useEffect(() => {
    // worker = new WebWorker(worker);
  }, []);
  return (
    <div className="App">
      <h1>Hello CodeSandbox</h1>
      <button onClick={buttonHan}>BTN</button>

      <h2>Start editing to see some magic happen!</h2>
    </div>
  );
}

The iissue is when I am creating a object of worker in useEffect in the below line.

 // worker = new WebWorker(worker);

On button click, I want to send trigger to my worker for calculation.


Solution

  • You have two lines that are in conflict.

    import worker from "./workerfile";
    

    and

        // worker = new WebWorker(worker);
    

    You first import from a file and assign the value to a variable named worker.

    You should not then later change that value. If you must use that name you can shadow-scope your variable by including a block-scope keyword such as let or const. But you can also just redefine the variable name (e.g. myWorker or similar).