Repository: zeit/swr (ts)

Issue:
When using SSR and initialData, is it possible to prevent first validation after render?
In `getInitialProps()` I call my fetcher function which queries the db for data. I pass that initial data to `useSWR` as `initialData` option. However, as soon as it renders, it queries the server again with the same end point (returning the same data set). I would expect that it would not query on render if `initialData` is passed, or there would be an option to prevent this.

I would like to prevent the server getting hit twice in a short timeframe with the same endpoint.

Pull request description:
skip immediate revalidation when initalData is provided
This fixes #194.

I wasn't sure if this should be set via another option or not but if so let me know and I can update.


Patch:
diff --git a/src/use-swr.ts b/src/use-swr.ts
index 9c9e510..d6d21fb 100644
--- a/src/use-swr.ts
+++ b/src/use-swr.ts
@@ -382,16 +382,18 @@ function useSWR<Data = any, Error = any>(
     const softRevalidate = () => revalidate({ dedupe: true })
 
     // trigger a revalidation
-    if (
-      typeof latestKeyedData !== 'undefined' &&
-      !IS_SERVER &&
-      window['requestIdleCallback']
-    ) {
-      // delay revalidate if there's cache
-      // to not block the rendering
-      window['requestIdleCallback'](softRevalidate)
-    } else {
-      softRevalidate()
+    if (!config.initialData) {
+      if (
+        typeof latestKeyedData !== 'undefined' &&
+        !IS_SERVER &&
+        window['requestIdleCallback']
+      ) {
+        // delay revalidate if there's cache
+        // to not block the rendering
+        window['requestIdleCallback'](softRevalidate)
+      } else {
+        softRevalidate()
+      }
     }
 
     // whenever the window gets focused, revalidate


Test patch:
diff --git a/test/use-swr.test.tsx b/test/use-swr.test.tsx
index 64b964d..bdb7cbd 100644
--- a/test/use-swr.test.tsx
+++ b/test/use-swr.test.tsx
@@ -243,8 +243,10 @@ describe('useSWR', () => {
   })
 
   it('should accept initial data', async () => {
+    const fetcher = jest.fn(() => 'SWR')
+
     function Page() {
-      const { data } = useSWR('initial-data-1', () => 'SWR', {
+      const { data } = useSWR('initial-data-1', fetcher, {
         initialData: 'Initial'
       })
       return <div>hello, {data}</div>
@@ -252,13 +254,10 @@ describe('useSWR', () => {
 
     const { container } = render(<Page />)
 
+    expect(fetcher).not.toBeCalled()
     expect(container.firstChild.textContent).toMatchInlineSnapshot(
       `"hello, Initial"`
     )
-    await waitForDomChange({ container }) // mount
-    expect(container.firstChild.textContent).toMatchInlineSnapshot(
-      `"hello, SWR"`
-    )
   })
 
   it('should set config as second parameter', async () => {