Problem
After changing source in useImage hook eg. via useState, hook state does not reset to "loading state" ({ image: undefined, error: undefined })
const [random, setRandom] = React.useState<number>(0)
const { image, error } = useImage({ url: `https://picsum.photos/seed/${random}/200/300` })
return (
<View>
{image ? <NitroImage image={image} style={{ width: 170, height: 170 }} /> : <Text>Loading...</Text>}
{error ? error.message : null}
<Button title="Random Image" onPress={() => setRandom(prev => prev + 1)} />
</View>
)
In this example, after we update url I would expect it, state to be reset (image should be undefined) as we are now again in loading state
Now, even if we update "source" and it returns "new" Result, NitroImage does not update displayed image
Proposed Solution
Add clean up function to useEffect in useImage hook, and set image to default/loading state
export function useImage(source: AsyncImageSource): Result {
const [image, setImage] = useState<Result>({
image: undefined,
error: undefined,
});
// biome-ignore lint: The dependencies array is a bit hacky.
useEffect(() => {
(async () => {
try {
const result = await loadImage(source);
setImage({ image: result, error: undefined });
} catch (e) {
const error = e instanceof Error ? e : new Error(`${e}`);
setImage({ image: undefined, error: error });
}
})();
// here add cleanup function so once deps did change we are back to default/loading state
return () => {
setImage({ image: undefined, error: undefined });
}
}, [isHybridObject(source) ? source : JSON.stringify(source)]);
return image;
}
If this is something we can do, I can make PR 😄
Problem
After changing
sourceinuseImagehook eg. via useState, hook state does not reset to "loading state" ({ image: undefined, error: undefined })In this example, after we update url I would expect it, state to be reset (
imageshould beundefined) as we are now again in loading stateNow, even if we update "source" and it returns "new"
Result,NitroImagedoes not update displayed imageProposed Solution
Add clean up function to
useEffectinuseImagehook, and set image to default/loading stateIf this is something we can do, I can make PR 😄