I applied the react solution from @MariuszWiazowski, it works without Ionic however when using <ImageWithAuth/>
component in several places in my app I noticed it sometimes displays image alt instead of image itself.
It seems the problem occurs when image is already fetched but img.current
is still null. To avoid it we should save fetched image to component state using useState
and update img.current.src
only after we have fetchedImage
and img ref is not null.
Something like this:
export const ImageWithAuth: React.FC<ImageWithAuthProps> = ({ url }) => {
const [fetchedImage, setFetchedImage] = useState<string | undefined>()
const img: React.Ref<HTMLImageElement> = React.createRef()
useEffect(() => {
axios
.get(`${url}`, {
responseType: 'arraybuffer',
headers: {
Accept: 'image/jpeg',
},
})
.then((res) => {
const blob = new Blob([res.data], {
type: 'image/jpeg',
})
const objectURL = URL.createObjectURL(blob)
setFetchedImage(objectURL)
})
}, [url])
useEffect(() => {
// Make sure img.current is not null and image is fetched
if (img.current && fetchedImage) {
img.current.src = fetchedImage
}
}, [fetchedImage])
return <img src={''} alt={'Loading...'} ref={img} />
}
export default ImageWithAuth