0

So I am trying to upload files with react. To check if there is actually a file to upload, I found the following code:

if( Object.keys(file).length !== 0){
  do things
}

However, if I have a simple code like this:

import '../styles/App.css';
import React,{useState} from "react";

function Home() {
    const [file, setFile] = useState([]);

    const object1 = {
        a: 'somestring',
        b: 42,
        c: false
    };

    function handleSubmit(){
        console.log("file: " + file + ", key length: " + Object.keys(file).length)
        console.log("test: " + Object.keys(object1).length)
    }

    return (
        <div className="App">
            <div className="App-header">
                <p>
                    Home
                </p>
                <input
                    type="file"
                    onChange={(e)=>{setFile(e.target.files[0])}}
                />
                <button
                onClick={handleSubmit}>Test
                </button>
            </div>
        </div>
    );
}

export default Home;

then the first console log always attests me (after choosing a file of my own) that there are no keys in the file-state, while the object1 works like a charm.

Any advice?

underscore_d
  • 6,309
  • 3
  • 38
  • 64
Gauerdia
  • 45
  • 5
  • https://stackoverflow.com/questions/679915/how-do-i-test-for-an-empty-javascript-object :) – AdamKniec Jan 14 '22 at 15:39
  • 1
    Does this answer your question? [How do I test for an empty JavaScript object?](https://stackoverflow.com/questions/679915/how-do-i-test-for-an-empty-javascript-object) – AdamKniec Jan 14 '22 at 15:40

0 Answers0