-
Notifications
You must be signed in to change notification settings - Fork 5
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Add FetchedImage to use IPC to load image dynamically
- Loading branch information
1 parent
3b50e41
commit 9bc9b0f
Showing
2 changed files
with
69 additions
and
2 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,57 @@ | ||
import React from 'react'; | ||
import { AccountInfo } from '../../shared-types'; | ||
|
||
export function FetchedImage({ | ||
src, | ||
account, | ||
}: { | ||
src: string; | ||
account: AccountInfo; | ||
}) { | ||
const [imgSrc, setImgSrc] = React.useState<string | undefined>(); | ||
const isFetched = React.useRef<boolean>(false); | ||
|
||
const fetchImage = React.useCallback(async () => { | ||
const bytes = await window.electronApi.getRawImage(src, account); | ||
if ('error' in bytes) { | ||
console.error(`Error loading image ${src}`, bytes.error); | ||
return; | ||
} | ||
const blob = new Blob(bytes); | ||
const imageObjectURL = URL.createObjectURL(blob); | ||
setImgSrc(imageObjectURL); | ||
}, [src]); | ||
|
||
React.useEffect(() => { | ||
return () => { | ||
// Make sure to reset isFetched if the component is unmounted. | ||
isFetched.current = false; | ||
}; | ||
}, []); | ||
|
||
React.useEffect(() => { | ||
if (isFetched.current) { | ||
return; | ||
} | ||
isFetched.current = true; | ||
fetchImage(); | ||
}, [fetchImage]); | ||
|
||
if (!imgSrc) { | ||
return <PlaceholderComponent />; | ||
} | ||
return <img src={imgSrc} />; | ||
} | ||
|
||
function PlaceholderComponent() { | ||
return React.createElement( | ||
'svg', | ||
{ width: '33', height: '33' }, | ||
React.createElement('circle', { | ||
cx: '16', | ||
cy: '16', | ||
r: '15', | ||
fill: 'orange', | ||
}) | ||
); | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters