Search code examples
javascriptreactjsfetchquill

Quill undefined when uploading a file from local machine


I am a beginner working with React.js and Quill. I am trying to upload a file from my local machine by rewriting existing imageHandler. It does take the file, but do not upload it. The error is following: TypeError: Cannot read property 'quill' of undefined. Here is my code so far:

function imageHandler() {
    console.log('Image Handler called');

    const input = document.createElement('input');
    input.setAttribute('type', 'file');
    input.setAttribute('accept', 'image/*');
    input.click();
    input.onchange = async function () {
        const file = input.files[0];
        console.log('User trying to upload this:', file);

        const formData = new FormData()
        if (file !== null) {
            formData.append('file', file)
        }
        fetch('https://smartquestionapi.advancity.net/Image', {
            method: 'POST',
            headers: {
                'Accept': 'application/json',
                'Content-Type': 'multipart/form-data',
            },
            body: formData
        }).then(function (response) {
            if (response.ok) {
                return response.json()
            } else {
                return { "error": true }
            }
        }).then(function (json) {
            console.log(file.name);
            var cursorPosition = this.quill.getSelection();
            var imagePath = "https://smartquestionapi.advancity.net/Images/" + file.name;
            
            this.quill.insertEmbed(cursorPosition.index, 'image', imagePath, Quill.sources.USER);
            return json;
        }).catch(err => {
            console.log("eror: ", err);
        })
    }.bind(this);
}

The code crushes exactly in then(function (json){ function.


Solution

  • I think is because you are not binding this in this part:

    .then(function (json) {
                console.log(file.name);
                var cursorPosition = this.quill.getSelection();
    

    You can solve it with an arrow function:

        .then((json) => {
                console.log(file.name);
                var cursorPosition = this.quill.getSelection();
    

    Take also a look here, to see the differences between function(){} and (args..) => {}