• Empleos
  • Sobre nosotros
  • profesionales
    • Inicio
    • Empleos
    • Cursos y retos
  • empresas
    • Inicio
    • Publicar vacante
    • Nuestro proceso
    • Precios
    • Evaluaciones
    • Nómina
    • Blog
    • Comercial
    • Calculadora de salario

0

118
Vistas
Hooks and webworkers

Is there a way for a webworker to use a react hook?

I am using Apollo Client to perform useLazyQuery which is a custom hook.

But the actual operation takes quite long and times out most often!

I want to run this on another thread to not disrupt the main application.

almost 3 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

Although I'm not sure whether your timeout problem would be fixed by executing the query in a webworker, the easiest way to achieve that (without considering pending/error states) would be something like this:

worker.js

self.addEventListener('message', async event => {
  const {apolloClient, query} = e.data;
  const result = await apolloClient.query({query});  
  self.postMessage(result);
  self.close();
});
App.jsx

const query = gql`Some query here`;

const useWebWorkerQuery = query => {
  const apolloClient = useApolloClient();
  const [result, setResult] = useState(null);

  useEffect(() => {
    const worker = new Worker('worker.js');
    worker.postMessage({apolloClient, query});
    worker.onmessage = event => setResult(event.data);
  }, []);
};

const App = () => {
  const result = useWebWorkerQuery(query);

  useEffect(() => {
    if(result) {
      // Do something once query completes
    }
  }, [result]);

  return null;
};

export default App;
almost 3 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Nuestro proceso Comercial
Legal
Términos y condiciones Política de privacidad
© 2025 PeakU Inc. All Rights Reserved.

Andres GPT

Recomiéndame algunas ofertas
Necesito ayuda