i am trying to upload a file into a state variable.
function CreateCarouselPost() {
const [file, setFile] = useState(null);
const handleFileUpload = (e) => {
setFile(e.target.files[0]);
console.log(file); // file is still null
}
return (
<div className='create-carousel-container'>
<h2 className='create-carousel-header'>Add Images and Videos</h2>
<div className='create-carousel-grid'>
<div className='add-image-video-card grid-item'>
<input
className='carousel-file-upload'
type='file'
name='content'
accept='image/*,video/*'
onChange={handleFileUpload}
/>
</div>
</div>
</div>
);
}
But i go to know that setState is asynchronous and can take time. So when i console.log file immediately after setFile, file is still null. When i upload another file, it has contents of previous file. So, i tried to wait for it by using Promises but i couldn't get it to work.
import React, { useState, useEffect } from 'react';
import AddIcon from '@material-ui/icons/Add';
import './styles/Carousel.css';
function CreateCarouselPost() {
const [file, setFile] = useState(null);
const uploadFile = (file) => {
return new Promise((resolve) => {
setFile(file);
resolve();
});
};
const handleFileUpload = (e) => {
uploadFile(e.target.files[0]).then(() => {
console.log('file = ', file);
});
};
return (
<div className='create-carousel-container'>
<h2 className='create-carousel-header'>Add Images and Videos</h2>
<div className='create-carousel-grid'>
<div className='add-image-video-card grid-item'>
<input
className='carousel-file-upload'
type='file'
name='content'
accept='image/*,video/*'
onChange={handleFileUpload}
/>
</div>
</div>
</div>
);
}
export default CreateCarouselPost;
As far as my understanding Promise will be resolved after all the code inside is executed and then resolve function is called. So i tried to place it inside Promise and tried to access the file state inside the resolve(). But it turns out that the issue is still same (not getting the latest value). please help to do it in right way.