Topic: Attachment thumbnails disappear after changing an unrelated form field
owlStack77
asked a week ago
Our attachment picker shows a thumbnail for each local image. The previews load correctly, but editing the description field makes some of them disappear. The selected File objects are still in state and the request contains the correct attachments.
We create object URLs inside a preview effect and revoke them in its cleanup. The effect depends on the entire form object because the files are stored there. Could this cleanup be running while an existing thumbnail still uses its URL?
Mateusz Lazaru
staff answered a week ago
Keep the files array separate from unrelated form fields and make the preview effect depend on that array. A cleanup runs before an effect runs again, so revoking a URL that the next render continues to use can leave an image pointing to a released resource.
Create a fresh group of URLs when the file selection changes and revoke exactly that group in the matching cleanup. Please share the effect and the thumbnail JSX if it still happens; we should also check that a parent is not mutating the existing files array.
https://react.dev/reference/react-dom/components/input
owlStack77 commented a week ago
The cleanup was indeed tied to the whole form, and the preview list lived in a separate state value. I reduced the component to this example. The files array itself stays unchanged when the description changes.
useEffect(() => {
const urls = form.files.map(file => URL.createObjectURL(file));
setPreviews(urls);
return () => urls.forEach(url => URL.revokeObjectURL(url));
}, [form]);
Mateusz Lazaru
staff answered a week ago
Depend on form.files instead. This keeps the same preview URLs while another form field changes and replaces them when the attachment array changes. Make sure add/remove handlers produce a new files array rather than modifying the current one.
useEffect(() => {
const urls = form.files.map(file => URL.createObjectURL(file));
setPreviews(urls);
return () => urls.forEach(url => URL.revokeObjectURL(url));
}, [form.files]);
FREE CONSULTATION
Hire our experts to build a dedicated project. We'll analyze your business requirements, for free.
Answered
- User: Free
- Premium support: No
- Technology: MDB React
- MDB Version: MDB5 9.0.0
- Device: Laptop
- Browser: Chrome
- OS: Windows 11
- Provided sample code: No
- Provided link: No