Skip to main content

Images and other Media

Reactive Data Client can also fetch media, so images and other binary data get Suspense and render-as-you-fetch.

Storing ArrayBuffer​

Do not use Resource or Entity for binary data. They model objects with keys. Define an Endpoint instead.

import { Endpoint } from '@data-client/rest';

export const getPhoto = new Endpoint(async ({ userId }: { userId: string }) => {
const response = await fetch(`/users/${userId}/photo`);
const photoArrayBuffer = await response.arrayBuffer();

return photoArrayBuffer;
});
// photo is typed as ArrayBuffer
const photo = useSuspense(getPhoto, { userId });

Just Images​

Images can suspend as well, so a Suspense boundary waits for them to load. This works best with render-as-you-fetch.

@data-client/img has an <Img /> component that suspends, and a getImage endpoint to prefetch.

Installation​

npm install --save @data-client/img
Run in your terminal

Usage​

Profile.tsx
import React from 'react';
import { useSuspense } from '@data-client/react';
import { Img } from '@data-client/img';
import { UserResource } from './resources/User';

export default function Profile({ username }: { username: string }) {
const user = useSuspense(UserResource.get, { username });
return (
<div>
<Img
src={user.img}
alt="React Logo"
style={{ height: '32px', width: '32px' }}
/>
<h2>{user.fullName}</h2>
</div>
);
}

Prefetching​

The example above waits for the user before the image request starts. If you can compute the image URL from the same parameters, start both requests at the same time:

Profile.tsx
import React from 'react';
import { useSuspense, useFetch } from '@data-client/react';
import { Img, getImage } from '@data-client/img';
import { UserResource } from './resources/User';

export default function Profile({ username }: { username: string }) {
const imageSrc = `/profile_images/${username}`;
useFetch(getImage, { src: imageSrc });
const user = useSuspense(UserResource.get, { username });
return (
<div>
<Img
src={imageSrc}
alt="React Logo"
style={{ height: '32px', width: '32px' }}
/>
<h2>{user.fullName}</h2>
</div>
);
}

With render-as-you-fetch, call Controller.fetch() with the getImage Endpoint to preload the image.