I have function in parent component
const getFilename= (filedata)=>
{
console.log(filedata);
}
And pass call a child component from parent
<FileUpload getFieDetails={getFilename} />
Childcomponent function:
const [files, setFiles] = useState([])
const uploadHandler = (event) => {
const file = event.target.files[0];
console.log(file);
if(!file) return;
file.isUploading = true;
setFiles((prevState) => [...prevState, file])
props.getFieDetails(files);
)
}
when i console files from child component all the value is listing.But in parent component one data is always missing.Thanks in advance
3
Answers
Since
useState
is aasync
function, the last data you are adding in thesetFiles
won’t be updated in thefiles
whenprops.getFieDetails(files)
is called.I would suggest, you call the it inside a
useEffect
in the child component, so that it will be executed every time file changes in theuploadHandler
functionThe problem is that
setFiles
is asynchronous. When you callsetFiles(...)
, React re-renders your component and thefiles
state will be stale until the next render. Therefore, callingprops.getFileDetails(files)
immediately after will pass the previousfiles
state.Option 1:
Create a new array and call
setFiles
andprops.getFilename
with the new value.Option 2:
Call
props.getFileDetails
in auseEffect
.You can call
getFieDetails
inside setFiles callbacklike this: