Skip to content
Advertisement

how to put a file in state variable with react hooks

I’m trying to upload a picture using react hooks

const [picture, setPicture] = useState();

const onChangePicture = e => {
    console.log('picture: ', picture);
    setPicture(...picture, e.target.files[0]);
};

<input
  type="file"
  //style={{ display: 'none' }}
  onChange={e => onChangePicture(e)}
/>

however I’m getting the following error:

Uncaught TypeError: picture is not iterable

when I change the onChangePicture to

setPicture(picture, e.target.files[0]) 

the picture variable is undefined,

any help would be appreciated.

Advertisement

Answer

I think you meant to do:

setPicture([...picture, e.target.files[0]]);

This will concatenate the first file to all current files.

Remember to use const [picture, setPicture] = useState([]); as to make sure it doesn’t break the first time around

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement