DEV Community

Will
Will

Posted on

Handling suspense state in components, rather than cache

In my previous post I posed a question about how to model data fetching based on domain, rather than request. Now I'd like to pose a concrete technical question that I came out of that with:

Can we move suspending out of the cache, and into the component?

High level example:

function PartsEditor({ part }) {
  let suspend = useSuspense();
  let [partName, updateName] = useState(part.name);

  let updatePart = () => {
    // triggers a re-render that suspends the component
    let resume = suspend();
    updatePartCache(part.id, { partName })
      // once we've settled updating the part cache
      // settle the suspender and continue rendering
      .then(() => resume());
  };

  return (
    <div>
      <div>
        Part name: <input value={partName} onChange={e => updateName(e.target.value)} />
      </div>
      <button onClick={updatePart}>Update</button>
    </div>
  );
}

This would allow components that consume caches to vary their suspension behavior based on the context. For instance, reading from the cache would involve subscribing to it and optionally handling specific events:

function PartsList() {
  let suspend = useSuspense();
  let [parts] = useCache(
     partsCache,
     {
       readMany() {
         let resume = suspend();
         // called on cache settle
         return resume;
       }
     }
  );
}

What do you think? Would appreciate feedback!

Top comments (0)