dai-shi / react-suspense-fetch

[NOT MAINTAINED] A low-level library for React Suspense for Data Fetching
MIT License
296 stars 8 forks source link

Add entries to internal cache #47

Closed axelboc closed 2 years ago

axelboc commented 2 years ago

I'm using a store to fetch entities organised in a tree structure. Each entity is identified by a path and can either be, let's say a folder or a file (but I don't know which one in advance).

To save network requests, when I fetch a folder, the response already includes the files it contains. What I'd like to do is to store those files in the store's internal cache against their respective paths, so that if they are ever requested directly, they do not get fetched again.

Right now, I'm achieving this behaviour by wrapping the fetch function I'm passing to the store and maintaining my own child cache:

const childCache = new Map<string, Entity>();

const store = createFetchStore(async (path: string) => {
  const cachedEntity = childCache.get(path);
  if (cachedEntity) {
    return cachedEntity;
  }

  const entity = await fetchEntity(path);

  if (isFolder(entity)) {
    // Cache children ...
    entity.children.forEach((child) => {
      // ... except sub-folders, since we do want those to be re-fetched fully (with their children)
      if (!isFolder(child)) {
        childCache.set(child.path, child);
      }
    });
  }

  return entity;
});

This code could be simplified a lot if I had a way to add entries to the store's internal cache. My initial thought was that store.prefetch() could perhaps receive a resolved value as second argument. šŸ¤·

dai-shi commented 2 years ago

Interesting. We have preloaded, but do you want to set an entry after creating the store?

axelboc commented 2 years ago

Yeah, precisely šŸ‘

axelboc commented 2 years ago

Could also be a seed() method, but I thought prefetch could already do the job easily.

dai-shi commented 2 years ago

I would think adding a new method to the store, but I wonder about naming. preload doesn't sound super correct.

dai-shi commented 2 years ago

No, it's slightly different from prefetch.

dai-shi commented 2 years ago

seed sounds you can only set just once, but we could call it as many times as we want, right?

axelboc commented 2 years ago

Yeah, I'd need to either call it inside forEach, or pass an array of key/value entries.

axelboc commented 2 years ago

What about store.cache()? It has the merit of being explicit: we cache something into the store. šŸ˜

dai-shi commented 2 years ago

That sounds vague to me. It's confusing in the library code too. How about store.preset()?

axelboc commented 2 years ago

Yeah, sure!

dai-shi commented 2 years ago

Please try this. https://ci.codesandbox.io/status/dai-shi/react-suspense-fetch/pr/48 Find "Local Install Instructions" ā˜ļø

axelboc commented 2 years ago

Works like a charm, thanks a lot! āœØ

dai-shi commented 2 years ago

https://www.npmjs.com/package/react-suspense-fetch/v/0.6.0