code-forge-io / code-forge-io/remix-client-cache

Support caching for streamed responses

Abierto
#7 3 comentarios 1 reacción 0 asignados Ver en GitHub
Lenguaje dominante
TypeScript
Estrellas
247
Forks
3
Métricas de merge de PR
Sin PR fusionados en 30 d

Descripción

[Stackblitz](https://stackblitz.com/~/github.com/predaytor/remix-test?file=app/routes/test.tsx)

When using `defer` to stream a response from a loader that returned a promise which later used in a boundary, we cannot properly serialize the promise to store say in localStorage or IndexedDB (`JSON.stringify` will result in an empty object `{}`). The only way to store this type of data is directly in memory, so on the next navigation, `clientLoader` will return fulfilled promise with the data, rather than calling the server `loader'.
```tsx
let cache: SerializeFrom;
export const clientLoader = defineClientLoader(async ({ serverLoader }) => {
if (!cache) {
cache = await serverLoader();
}

return cache;
});

clientLoader.hydrate = true;
```
By using `remix-client-cache`, we can create an adapter for when we need to cache streaming responses, rather than relying on a global setting using, for example, `localStorage`.
```ts
import { lru } from 'tiny-lru';
import { type CacheAdapter, createCacheAdapter } from 'remix-client-cache';

const cache = lru(100);

class LRUAdapter implements CacheAdapter {
async getItem(key: string) {
return cache.get(key);
}

async setItem(key: string, value: any) {
return cache.set(key, value);
}

async removeItem(key: string) {
return cache.delete(key);
}
}

export const { adapter: lruAdapter } = createCacheAdapter(() => new LRUAdapter());
```

`routes/index.tsx`:
```tsx
import { defer } from '@remix-run/node';
import { Await, ClientLoaderFunctionArgs, Link } from '@remix-run/react';
import { Suspense } from 'react';
import { cacheClientLoader, useCachedLoaderData } from 'remix-client-cache';
import { lruAdapter } from '~/client-cache-adapter';

async function getQueryData() {
await new Promise((resolve) => setTimeout(resolve, 3000));
return { data: [{ id: 1 }] };
}

export async function loader() {
const query = getQueryData();

return defer({
query,
});
}

export const clientLoader = (args: ClientLoaderFunctionArgs) => cacheClientLoader(args, { adapter: lruAdapter });
clientLoader.hydrate = true;

export default function Page() {
const { query } = useCachedLoaderData();

return (
<>
Home






{({ data }) => (


    {data?.map((entry) =>
  • {entry.id}
  • )}

)}



);
}
```
This opens up a question whether it's a good idea to store data in server memory, it would be interesting if we could transform fulfilled promises using a library like [`turbo-stream`](https://github.com/jacob-ebey/turbo-stream) to store on the client-side or use a web worker and decode to the original form for consumption by .

---

There is currently a bug where a returned promise from the cache has already been fulfilled, the internal logic of `remix-client-cache` cannot understand when a revalidation should occur, or fulfilled data is currently present, since we must store promises directly in memory and not as a string.
https://github.com/forge42dev/remix-client-cache/blob/main/src/index.tsx#L116-L140
```tsx
// Unpack deferred data from the server
useEffect(() => {
let isMounted = true;
if (loaderData.deferredServerData) {
loaderData.deferredServerData.then((newData: any) => {
if (isMounted) {
adapter.setItem(loaderData.key, newData);
setFreshData(newData);
}
});
}
return () => {
isMounted = false;
};
}, [loaderData, adapter]);

// Update the cache if the data changes
useEffect(() => {
if (
loaderData.serverData &&
JSON.stringify(loaderData.serverData) !== JSON.stringify(freshData)
) {
setFreshData(loaderData.serverData);
}
}, [loaderData?.serverData, freshData]);
```

Guía de contribución

No hay ninguna guía de contribución indexada para este repositorio

Línea de trabajo

Comienza con src/index.tsx, líneas 116-140, y reproduce la ruta de una Promise cumplida del ejemplo enlazado de StackBlitz/routes/index.tsx. Traza cómo se comparan deferredServerData, serverData, freshData y adapter; terminado significa que la caché distingue los datos almacenados en caché cuya Promise se ha cumplido de los datos que requieren revalidación, con un comportamiento verificado.

Escrito por el modelo de indexación a partir del texto del issue.

Evaluación

Stack tecnológico
react, typescript
Área
frontend, performance
Tipo de issue
Error
Dificultad
5/5
Tiempo estimado
Más de una semana
Estado de actividad
Estancado
Claridad
Necesita aclaración
Aptitud para principiantes
30/100

Recibe los nuevos issues en tu correo

Un resumen breve de issues de GitHub para principiantes.