When you enable suspense , how do SWR fetches both data and code parallelly to support code and data preloading
When you enable Suspense it will
The idea of the suspense mode is that you never receive data as undefined, your component got suspended and you handle the fallback using React.Suspense instead.
You can check how it works starting here https://github.com/zeit/swr/blob/master/src/use-swr.ts#L448
It doesn鈥檛 handle code preloading
react-query has a prefetchQuery function for doing data pre-fetch, this would be 馃挴 to have with swr: https://github.com/tannerlinsley/react-query#prefetchQuery
You could do that using mutate.
import { mutate } from "swr";
mutate("/api/resource/1", {}, true);
The last true (which is the default value so you don't really need it) will tell SWR to revalidate that data, so you pass an empty data and then let SWR fetch the real one for you.
You could also actually fetch the data and then run mutate.
import { mutate } from "swr";
const data = await fetch("/api/resource/1").then(res => res.json();
mutate("/api/resource/1", data, false);
In this case since we already fetched the data we tell mutate to don't revalidate it, it will do it however once a component requiring this data is rendered tho.
brilliant! i'm totally wrapping that up into a util
actually, digging into the source a bit, I don't think using mutate would behave the same. If we are pre-fetching, then the hook hasn't been called yet, so there is no CACHE_REVALIDATOR for the key set yet. The idea with pre-fetch being that we would be able to start loading data before the component rendered.
@tamagokun it does. Because it will set the cache before component mounts.
Although we鈥檙e working on another option to make prefetching even more easier and faster (as I explained here https://github.com/zeit/swr/issues/11#issuecomment-551371673).
I see, looking at those examples in the comment in this thread, the first mutate wouldn't start the fetch until the hook was created, but the 2nd one would definitely work. Looking forward to see what comes out of #11 :v:
Most helpful comment
When you enable Suspense it will
The idea of the suspense mode is that you never receive data as undefined, your component got suspended and you handle the fallback using React.Suspense instead.
You can check how it works starting here https://github.com/zeit/swr/blob/master/src/use-swr.ts#L448
It doesn鈥檛 handle code preloading