Bug: useState won't update ui when FileList type object set
See original GitHub issueI use useState hook to track files change in html input element. When the file changes, console can output correctly when change event fires. but setFileList not work correctly,useEffect didn’t be called and UI did’d be updated.
the first time I choose a image works fine, but the second time works not correctly
React version:react@16.12.0
const [fileList, setFileList] = useState<FileList | null>()
const handleImageChange: ChangeEventHandler<HTMLInputElement> = (e) => {
const { target: { files } } = e
setFileList(files)
}
useEffect(() => {
console.log('file list changed: ', fileList) // nothing happened
}, [fileList])
Issue Analytics
- State:
- Created 4 years ago
- Comments:7
Top Results From Across the Web
The useState set method is not reflecting a change immediately
Component or React.PureComponent , the state update using the updater provided by useState hook is also asynchronous, and will not be reflected immediately....
Read more >Steps to Solve Changes Not Reflecting When useState Set ...
Methods to solve the error when the useState set method is not reflecting an immediate change: · Using the “useEffect” hook: · Try...
Read more >Using the FileReader API to preview images in React
The FileReader API can be tricky to use, but it provides a handy feature that allows users to preview images before uploading to...
Read more >How to Upload Files With React - Code Frontend
Uploading a single file · First, we add an input element with type="file" attribute. · We can store the selected file in React...
Read more >Upload - Ant Design
Use defaultFileList for uploaded files when page init. expand code ... by configuring fileList . You can accomplish all kinds of customed functions....
Read more >
Top Related Medium Post
No results found
Top Related StackOverflow Question
No results found
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free
Top Related Reddit Thread
No results found
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Dev.to Post
No results found
Top Related Hashnode Post
No results found
@Ayman-Moukhtar Yes, need to point out that,
e.target.files
and[...e.target.files]
are different types, the former is a FileList other than Array.@yuquanwang You’re right, i was able to reproduce on firefox version
73.0.1
, the reason is that firefox re-uses the same array for appending/removing the newly added files to the input element. as a result:That’s why react doesn’t re-render, as the state didn’t change basically, so there is no need - from react’s perspective - for the component to re-render. As your workaround suggested, you would be fine just changing the array reference
setFileList([...e.target.files]);