mrousavy / mrousavy/react-native-nitro-image
Reset state of `useImage` after dependency changed
Nobody has claimed this yet.
- Dominant language
- TypeScript
- Stars
- 652
- Forks
- 37
- Avg merge
- 56m
- Merged PRs (30d)
- 6
Description
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 😄
Contributor guide
No contributing guide indexed for this repository
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
Start by locating the useImage hook and inspect its useEffect dependency handling and asynchronous loadImage result updates. Reproduce the source change shown in the issue; done means changing source returns to the loading state and NitroImage displays the newly loaded image.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- react-native, typescript
- Domain
- mobile
- Issue type
- Bug
- Difficulty
- 3/5
- Estimated time
- 1-2 days
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 35/100