bvaughn / suspense

Utilities for working with React Suspense

Home Page:https://suspense.vercel.app/

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Mutation

bvaughn opened this issue · comments

Currently thinking about supporting mutation with a hook like:

export function useCacheMutation<Params extends Array<any>, Value>(
  cache: Cache<Params, Value>,
  ...params: Params
): [isPending: boolean, mutate: (callback: MutationCallback) => Promise<void>] {
  // ...
}

Performing a mutation might look something like this then:

const [isPending, mutate] = useCacheMutation(cache, apiClient);

const save = (...params) => {
  mutate(async () => {
    await apiClient.save(...params);
  });
};

I think that– in order for this API to correctly schedule updates with React (after a cache mutation) this package would need to change the dependencies to the experimental release channel (for unstable_getCacheForType and unstable_useCacheRefresh). Unfortunately I think that would come with the significant downside of breaking the imperative API (e.g. getValue, fetchAsync) since those are called outside of React's render cycle.

On the other hand, we could move to a context based API and store the cache maps in state for invalidation but that would require moving the fetch calls to hooks as well (so components could subscribe/unsubscribe from updates). Not sure which of these is really a good path forward.

I think it might be possible for createCache to create its own record Map (in scope) that both suspense and imperative methods could use– but still call getRecordMap from inside of fetchSuspense (to let React know that the component is "subscribed" to the cache). This feels a bit hacky but may avoid both of the above downsides.


I might need to walk back the previous thoughts RE using getCacheForType to subscribe only. I think that won't work well enough.

Maybe there's a way that I could support React updates/transitions without breaking the imperative API– by storing data in two places:

  1. A static map that's created once (when the cache is configured) that holds values as they are loaded or cached via the imperative cache method.
  2. A React-managed map (via getCacheForType) that holds pending requests for missing values.

This is kind of how the React DevTools suspense cache works.

  • inspectedElementCache uses getCacheForType to get a reference to its record map (and useCacheRefresh to clear it when a record gets invalidated). It fetches data from a second cache (below).
  • inspectElementMutableSource is the second cache. It actually loads data from the React DevTools backend and stores loaded values in an LRU. When the backend reports that a value has changed, the LRU gets the newest value.

inspectedElementCache fetches the initial data on render, using Suspense. Then it polls inspectElementMutableSource for updates (using an interval, in an effect). If an update comes in, it schedules an update with React (using useCacheRefresh) and pre-seeds the new cache with the updated value.

  1. Pre-seeding the cache prevents the component from visibly suspending again, (and is kind of analogous to what the proposed useCacheMutation hook would enable by passing a cache callback to the mutate method).
  2. The transition update causes a re-render, which causes the component to pull in the new cache data.

A tricky thing about the way cache invalidation works in React (useCacheRefresh) that doesn't apply to React DevTools but would apply here– is that you can't evict a single cache. Calling useCacheRefresh clears all caches. However, that's where I think the 2nd static map could come in handy. Unless a value was explicitly evicted, then re-rendering could just read from that map directly and avoid suspending.

Can the isPending flag to also come from the suspender? That would make it possible to track it from a completely different branch in the tree

@cevr I think you're looking for useCacheStatus.

Can you please explain what's the difference between a mutation and a normal request?

Afaik, a mutation is a use case of a request that changes the state of my system, so mostly not cached and triggered manually or under certain conditions.
For that, you can create a normal cache with 0 deadline and evict when all subscribers unsubscribe. And mutate is just an aggressive refetch.

(Sorry. This issue isn't really meant to be a Q&A. GitHub issues aren't threaded so they don't work well for that. It's mostly meant for me to leave notes for myself, and plan the feature. In that vein– an update...)


I might need to walk back the previous thoughts RE using getCacheForType to subscribe only. I think that won't work well enough.

Maybe there's a way that I could support React updates/transitions without breaking the imperative API– by storing data in two places:

  1. A static map that's created once (when the cache is configured) that holds values as they are loaded or cached via the imperative cache method.
  2. A React-managed map (via getCacheForType) that holds pending requests for missing values.

This is kind of how the React DevTools suspense cache works.

  • inspectedElementCache uses getCacheForType to get a reference to its record map (and useCacheRefresh to clear it when a record gets invalidated). It fetches data from a second cache (below).
  • inspectElementMutableSource is the second cache. It actually loads data from the React DevTools backend and stores loaded values in an LRU. When the backend reports that a value has changed, the LRU gets the newest value.

inspectedElementCache fetches the initial data on render, using Suspense. Then it polls inspectElementMutableSource for updates (using an interval, in an effect). If an update comes in, it schedules an update with React (using useCacheRefresh) and pre-seeds the new cache with the updated value.

  1. Pre-seeding the cache prevents the component from visibly suspending again, (and is kind of analogous to what the proposed useCacheMutation hook would enable by passing a cache callback to the mutate method).
  2. The transition update causes a re-render, which causes the component to pull in the new cache data.

A tricky thing about the way cache invalidation works in React (useCacheRefresh) that doesn't apply to React DevTools but would apply here– is that you can't evict a single cache. Calling useCacheRefresh clears all caches. However, that's where I think the 2nd static map could come in handy. Unless a value was explicitly evicted, then re-rendering could just read from that map directly and avoid suspending.

The above idea seems like a promising direction based on a test app I wrote tonight. 👍🏼

Here's a walk through with a demo:
https://www.loom.com/share/55b645c9730a4958b8a2f91dfc19b72f