Reputation: 31565
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?
Upvotes: 5
Views: 2796
Reputation: 691
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.
Upvotes: 8