javascriptreactjstypescriptnext.jsref

How do I fix this TypeScript error in the ref Next.js


This ref is returning a typeScript error and I don't know how to fix it. the code works on local enviroment but is getting the error in the deploy process

const [quill, setQuill] = useState<any>(null)

const wrapperRef = useCallback(async (wrapper: any) => {
    if (typeof window !== 'undefined') {
      if (wrapper === null) return
      wrapper.innerHTML = ''
      const editor = document.createElement('div')
      wrapper.append(editor)
      const Quill = (await import('quill')).default
      const QuillCursors = (await import('quill-cursors')).default
      Quill.register('modules/cursors', QuillCursors)
      const q = new Quill(editor, {
        theme: 'snow',
        modules: {
          toolbar: TOOLBAR_OPTIONS,
          cursors: {
            transformOnTextChange: true,
          },
        },
      })
      setQuill(q)
    }
  }, [])


<div id="container" className="max-w-[800px]" ref={wrapperRef} />

Here is the error message

Type (wrapper: any) => Promise<void> is not assignable to type LegacyRef<HTMLDivElement> | undefined. Type (wrapper: any) => Promise<void> is not assignable to type (instance: HTMLDivElement | null) => void | (() => VoidOrUndefinedOnly). Type Promise<void> is not assignable to type void | (() => VoidOrUndefinedOnly)


Solution

  • The problem is that your wrapperRef function is an async function, which means it returns a promise. React doesn't expect a ref callback to return a promise. Instead, it expects a simple function that returns void (or nothing).

    In simpler terms, your function is doing something that React doesn't understand in this context. To fix this, you need to ensure that the wrapperRef function doesn't return a promise. I would recommend trying this:

      const [quill, setQuill] = useState<any>(null);
    
      const wrapperRef = useCallback((wrapper: HTMLDivElement | null) => {
        if (typeof window !== 'undefined' && wrapper !== null) {
          // Create an async function to handle the Quill setup
          const initializeQuill = async () => {
            wrapper.innerHTML = '';
            const editor = document.createElement('div');
            wrapper.append(editor);
            const Quill = (await import('quill')).default;
            const QuillCursors = (await import('quill-cursors')).default;
            Quill.register('modules/cursors', QuillCursors);
            const q = new Quill(editor, {
              theme: 'snow',
              modules: {
                toolbar: TOOLBAR_OPTIONS,
                cursors: {
                  transformOnTextChange: true,
                },
              },
            });
            setQuill(q);
          };
    
          // Call the async function without awaiting it
          initializeQuill();
        }
      }, []);
    
      return <div id="container" className="max-w-[800px]" ref={wrapperRef} />