CodePudding user response:
If you're fetching an image directly, you'll need to translate the fetched data response to a blob
and then create an object URL (URL.createObjectURL
) for the Image
tag to use as the source.
I've made a Stackblitz demo as well.
import Image from 'next/image';
import React from 'react';
import useSWR from 'swr';
const fetcher = (url) => fetch(url).then((res) => res.blob());
export default function App() {
const url = 'https://source.unsplash.com/random';
const { data, error } = useSWR(url, fetcher);
if (error) return 'An error has occurred.';
if (!data) return 'Loading...';
const dataUrl = URL.createObjectURL(data);
return (
<figure>
<style jsx>{`
figure {
position: relative;
width: 100%;
margin: 0;
padding-top: ${((200 / 200) * 100).toFixed(2)}%;
}
`}</style>
<Image src={dataUrl} alt={'test'} fill />
</figure>
);
}