Post

This isn’t in the effect, it’s in the promise callback, so it’s fine but still has footguns because of race conditions. Better to use use().

There are 3 use cases for fetch: - get data (GET) - refresh data (GET) - change data (POST, PUT, DELETE)

Starting in 19, you shouldn’t need to fetch in an effect for any of these use cases. Initial GET should be cached and read in render with use(). Refresh GET should clear the promise cache to trigger with use() again. POST/PUT/DELETE mutations should be done in event handlers with actions.

Cool, very curious how to implement revalidation after mutation. Is it documented? I have not found anything about that (but maybe I’m blind 😅)

I’m working on the docs, but if you’re not using a library the easiest way is to just set the promise in state function refresh() { startTransition(() => { setState(fetch(…)) }) }

Sure. But that's in response to an action. What about a fetch on mount? As in the example.

0 reposts0 likes

const cache = new Map(); function Component() { const [promise, setPromise] = useState(() => { if (!cache.has(url)) { cache.set(url, fetch(url).then(r => r.json())) } return cache.get(url); }); const data = use(promise); // render data ... }

This has been in the docs for a few years now in the example sandboxes for Suspense (albeit hidden since `use` wasn't stable). I'm working on adding this to the use() docs for 19 stable, but it's going to have a lot of caveats that you really should use a data fetching library and not this directly.