Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

QuillJS selection-change caches results for some reason

I have:

    useEffect(() => {
        if (quill) {
            quill.clipboard.dangerouslyPasteHTML(documentContent);
            quill.on('text-change', () => {
                setDocumentContent(quill.root.innerHTML);
            });

            quill.on('selection-change', (range, oldRange, source) => {
                console.log(documentState?.predictionStatus, range, oldRange, source);
            })

        }
    }, [quill]);

But the documentState.predictionStatus stays at it's original value. I think maybe because the value is cached somehow?

Any way to resolve?

Thanks!

like image 230
Shamoon Avatar asked Nov 07 '22 01:11

Shamoon


1 Answers

Does your code look like this ?

    const [documentState, setDocumentState] = useState();
    useEffect(() => {
        if (quill) {
            quill.clipboard.dangerouslyPasteHTML(documentContent);
            quill.on('text-change', () => {
                setDocumentContent(quill.root.innerHTML);
            });

            quill.on('selection-change', (range, oldRange, source) => {
                console.log(documentState?.predictionStatus, range, oldRange, source);
            })

        }
    }, [quill]);

You are trying to access documentState?.predictionStatus inside the handler function of quill.on which will likely to cause error since the function you pass to quill.on only remember the value original of documentState (because of closure)

To fix this, useRef instead for documentState

    const documentRef = useRef();

    useEffect(() => {
        if (quill) {
            quill.clipboard.dangerouslyPasteHTML(documentContent);
            quill.on('text-change', () => {
                setDocumentContent(quill.root.innerHTML);
            });

            quill.on('selection-change', (range, oldRange, source) => {
                console.log(documentRef.current?.predictionStatus, range, oldRange, source);
            })

        }
    }, [quill]);

/// somewhere in you code update documentRef
documentRef.current = newValue
like image 161
somallg Avatar answered Nov 11 '22 04:11

somallg