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.
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;