Next.JS 15 Web Worker ("Comlink") not working
Unanswered
French Bulldog posted this in #help-forum
French BulldogOP
I've searched online and they all have around the similar if not the same approach, besides the fact that they use TS (Typescript), they all relatively work. Besides mine.
5 Replies
French BulldogOP
// Address.js
'use client'
import { useEffect, useRef} from "react";
import { getCookie} from "cookies-next";
import * as Comlink from 'comlink'
export default function AddrWeb() {
const muniWorker = useRef(null);
useEffect(() => {
const init = () => {
const worker = new Worker(new URL('./municipality_worker.worker.js', import.meta.url), {type: 'module'})
muniWorker.current = Comlink.wrap(worker);
}
init();
}, [])
return (
<div onClick={async (e) => {
e.preventDefault();
console.log(muniWorker.current)
if(muniWorker.current){
try {
const res = await muniWorker.current.getMunicipality({m: 102809, key: getCookie('Key'), type: 'GET_MUNI'})
console.log(res)
}catch (e){
console.error(e)
}
}
}}>test</div>
)
}//municipality_worker.worker.js
import * as Comlink from 'comlink';
async function getMunicipality(e){
return e;
}
Comlink.expose({getMunicipality})I've tried native Web Workers and they seem to work (sometimes)
I only moved to Comlink because I've been trying to fix a bug with RHF (React Hook Form) where
.postMessage() doesn't post after calling it through OnChange like this<Controller name={name} render={({field}) => {
return <div data-lenis-prevent>
<Select
placeholder={loading ? 'Data is loading...' : disabled ? notSelectedMessage[index] : 'Select an option...'}
isDisabled={disabled}
id={id}
styles={{
control: (baseStyles, state) => ({
...baseStyles,
borderColor: state?.isFocused ? '#8b33ff' : '',
outlineColor: state?.isFocused ? '#8b33ff' : ''
}),
option: (baseStyles, state) => ({
...baseStyles,
backgroundColor: state?.isSelected || state?.isFocused ? '#8b33ff' : '',
color: state?.isSelected || state?.isFocused ? '#fff' : ''
}),
}}
instanceId={`${id}-0`}
// cacheOptions
// defaultOptions
options={data}
// value={getValues(`${name}.name`).length === 0 ? null : getValues(name)}
value={field?.value?.name?.length !== 0 ? field?.value : ''}
onChange={(e) => {
muniWorker.current.postMessage({m: e, key: getCookie('Key'), type: 'GET_MUNI', list: a})
field?.onChange(e);
}}
components={{Option: autoselectComponent, Control: autoselectInputComponent}}
getOptionLabel={(option) => `${option.name}`}
getOptionValue={(option) => option}
></Select>
{error}
</div>
}}></Controller>