wip
This commit is contained in:
@@ -0,0 +1,28 @@
|
||||
import { useEffect, useState } from "react";
|
||||
|
||||
/**
|
||||
* Creates an object URL for a Blob/File and revokes it when the source changes
|
||||
* or the component unmounts. Returns null when given null.
|
||||
*
|
||||
* `createObjectURL` is an imperative side effect that must run inside an effect,
|
||||
* so publishing the resulting URL to state here is genuine external-resource
|
||||
* synchronization rather than a render cascade — hence the single, contained
|
||||
* lint suppression below.
|
||||
*/
|
||||
export function useObjectUrl(source: Blob | null): string | null {
|
||||
const [url, setUrl] = useState<string | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
if (!source) return;
|
||||
const objectUrl = URL.createObjectURL(source);
|
||||
// Intended external-resource publish (see hook doc), not a render cascade.
|
||||
// eslint-disable-next-line react-hooks/set-state-in-effect
|
||||
setUrl(objectUrl);
|
||||
return () => {
|
||||
URL.revokeObjectURL(objectUrl);
|
||||
setUrl(null); // in cleanup, not the effect body — so no suppression needed
|
||||
};
|
||||
}, [source]);
|
||||
|
||||
return source ? url : null;
|
||||
}
|
||||
Reference in New Issue
Block a user