5

I'm getting the value of a File Object when using <inpu type="file" /> but when accessing e.target.files[0] I can't use it with spread operator or Object.assign.

I want to save the state with all of the File's properties and add some more data to it, but it doesn't work, it gives me a empty object.

Here is an codesandbox to reproduce it.

const onChange = e => {
    const file = e.target.files[0];
    console.log(file); // Logs File Object
    console.log({ ...file }); // Logs empty Object
    console.log(Object.assign({}, file)); // Logs empty Object
    setFile({ ...file, extraData: "hey" }); // Sets Object only with `extraData`
}

Why it doesn't spread the File properties?

1
  • @HereticMonkey This questions is also for understand better what is happening with the File Object and why it behaves that way, it isn't only for making the code cleaner. Do you know why it doesn't spread the properties? I don't and I would like to know why. Commented Jan 27, 2020 at 12:44

1 Answer 1

8

From MDN docs:

The Object.assign() method copies all enumerable own properties from one or more source objects to a target object. It returns the target object.

I'm guessing that you are referring to the inherited properties of the File object. If that is the case, the Object.assign method does not take them into account. The same goes for spread operator.

A solution would be to use lodash library and the method assignIn() which applies for both own and inherited object properties.

Sign up to request clarification or add additional context in comments.

1 Comment

Another example is JSON.stringify() - it also takes into account only enumerable properties. So JSON.stringify(file) or JSON.stringify(error) returns just {} ...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.