How do I provision an image in a React component using react-router and SSR?
I have built a react-router "framework mode" application to test some Cloudflare bindings. The KV binding works great and I was able to pull a text file from R2 in
loader() and process it fine. I am not able to come up with the secret sauce to work with an image file however. I have this working fine in a React SPA, the Cloudflare fetch() just processes the file in client mode. But on the server side, there is no URL.createObjectURL().
After many permutations I am left with the code, below. I pasted in the Typescript errors as I think they are part of the problem. Am I missing something simple??
import type { Route } from "./+types/r2_image";
export function meta({ }: Route.MetaArgs) {
return [
{ title: "Data Tests: R2 image file" },
{ name: "description", content: "Testing cloudflare bindings." },
];
}
export async function loader({ context }: Route.LoaderArgs) {
// Type 'R2ObjectBody | null' is not assignable to type 'R2ObjectBody'.
// Type 'null' is not assignable to type 'R2ObjectBody'.ts(2322)
// vvvvvvv
const r2Image: R2ObjectBody = await context.cloudflare.env.CROMR2.get('conan.png');
var image = await r2Image.blob();
return { data: image };
}
export default function R2Image({ loaderData }: Route.ComponentProps) {
// Types of property 'arrayBuffer' are incompatible.
// Type 'undefined' is not assignable to type '() => Promise<ArrayBuffer>'.ts(2345)
// vvvvvvvvvv
const image = URL.createObjectURL(loaderData.data);
// or
// const image = URL.createObjectURL(loaderData.arrayBuffer);
return (
<>
<h1>R2 Image File</h1>
<div>
<img src={image} />
</div>
</>
)
}
This code is available in a public repo, here: https://github.com/Omortis/framerr - thanks in advance for any pointers to documentation or prior art. Note that I am trying to get to this to work with any binary file (I need to pull PDFs too).GitHub
GitHub - Omortis/framerr: Testing the various Cloudflare bindings
Testing the various Cloudflare bindings. Contribute to Omortis/framerr development by creating an account on GitHub.
1 Reply
This code dumps an error to the console. I believe it is due to the type mismatch in the argument to
createObjectUrl()?
Failed to execute 'createObjectURL' on 'URL': Overload resolution failed.
Wow. No help, anywhere, in any forum. Is this just not possible or not a good idea?