Search code examples
javascriptreactjsdefineproperty

Object.defineProperty called on non-object in my react.js application


I was trying to change a file's name before uploading in my react.js application:

Here is the approach :

onInputChange = (e) =>{

    let newFileName='dp';
    if(e.target.files.length!==0){
        this.state.file=e.target.files[0];

        Object.defineProperty(this.state.file.name, 'name', {
            writable: true,
            value: newFileName
        });
        console.log(this.state.file);
    }
};

But the problem is, whenever this function gets called, I get an error saying : Object.defineProperty called on non-object

How this can be solved ?


Solution

  • You are defining a new property on a string primitive in the Object.defineProperty. The this.state.file.name is a string primitive not an object.

    const onInputChange = (e) =>{
        
            let newFileName='dp';
            if(e.target.files.length!==0){
                const file = e.target.files[0];
                // file is an object
                // Since file.name is read-only, this is not the proper way to change the name
                // For a file object writable is already true
                Object.defineProperty(file , 'name', {
                    value: newFileName
                });
                console.log(file.name);
       
                // Since file name is readonly, and cannot be changed after the File is created
                // This is an alternate way to set the name on a copy of the file object
                const blob = file.slice(0, file.size, file.type); 
                newFile = new File([blob], newFileName, {type: file.type});
                console.log(newFile.name);
           }
    };
    document.querySelector("#fileInput").addEventListener("change", onInputChange);
    Upload here:
    <input type="file" name="test" id="fileInput"/>

    Also to update the state do not directly mutate the this.state but instead use the setState() method to update it.