Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Improvements #148

Merged
merged 6 commits into from
Dec 2, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 27 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@ of `fetcher` and rerenders the component.
Note that `fetcher` can be any asynchronous function, so you can use your favourite data-fetching
library to handle that part.

Check out [swr.now.sh](https://swr.now.sh) for more demos of SWR.
Check out [swr.now.sh](https://swr.now.sh) for more demos of SWR, and [Examples](#examples) for the best practices.

<br/>

Expand Down Expand Up @@ -137,10 +137,11 @@ You can also use [global configuration](#global-configuration) to provide defaul
- [Dependent Fetching](#dependent-fetching)
- [Multiple Arguments](#multiple-arguments)
- [Manually Revalidate](#manually-revalidate)
- [Local Mutation](#local-mutation)
- [Mutation and Post Request](#mutation-and-post-request)
- [SSR with Next.js](#ssr-with-nextjs)
- [Suspense Mode](#suspense-mode)
- [Error Retries](#error-retries)
- [Prefetching Data](#prefetching-data)

### Global Configuration

Expand Down Expand Up @@ -309,7 +310,7 @@ function App () {
}
```

### Local Mutation
### Mutation and Post Request

In many cases, applying local mutations to data is a good way to make changes
feel faster — no need to wait for the remote source of data.
Expand Down Expand Up @@ -418,6 +419,29 @@ useSWR(key, fetcher, {
})
```

### Prefetching Data

There’re many ways to prefetch the data for SWR. For top level requests, [`rel="preload"`](https://developer.mozilla.org/en-US/docs/Web/HTML/Preloading_content) is highly recommended:

```html
<link rel="preload" href="/api/data" as="fetch" crossorigin="anonymous">
```

This will prefetch the data before the JavaScript starts downloading. And your incoming fetch requests will reuse the result (including SWR, of course).

Another choice is to prefetch the data conditionally. You can have a function to refetch and set the cache:

```js
function prefetch () {
mutate('/api/data', fetch('/api/data').then(res => res.json()))
// the second parameter is a Promise
// SWR will use the result when it resolves
}
```

And use it when you need to preload the **resources** (for example when [hovering](https://github.com/GoogleChromeLabs/quicklink) [a](https://github.com/guess-js/guess) [link](https://instant.page)).
Together with techniques like [page prefetching](https://nextjs.org/docs#prefetching-pages) in Next.js, you will be able to load both next page and data instantly.

<br/>

## Authors
Expand Down
14 changes: 13 additions & 1 deletion src/libs/hash.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,11 +9,23 @@ let counter = 0

// hashes an array of objects and returns a string
export default function hash(args: any[]): string {
if (!args.length) return ''
let key = 'arg'
for (let i = 0; i < args.length; ++i) {
let _hash
if (typeof args[i] !== 'object') {
_hash = String(args[i])
// need to consider the case that args[i] is a string:
// args[i] _hash
// "undefined" -> '"undefined"'
// undefined -> 'undefined'
// 123 -> '123'
// null -> 'null'
// "null" -> '"null"'
if (typeof args[i] === 'string') {
_hash = '"' + args[i] + '"'
} else {
_hash = String(args[i])
}
} else {
if (!table.has(args[i])) {
_hash = counter
Expand Down
15 changes: 5 additions & 10 deletions src/use-swr.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,6 @@ import defaultConfig, {
} from './config'
import SWRConfigContext from './swr-config-context'
import isDocumentVisible from './libs/is-document-visible'
import useHydration from './libs/use-hydration'
import throttle from './libs/throttle'
import hash from './libs/hash'

Expand Down Expand Up @@ -186,12 +185,8 @@ function useSWR<Data = any, Error = any>(
fn = config.fetcher
}

// it is fine to call `useHydration` conditionally here
// because `config.suspense` should never change
const shouldReadCache = config.suspense || !useHydration()
const initialData =
(shouldReadCache ? cacheGet(key) : undefined) || config.initialData
const initialError = shouldReadCache ? cacheGet(keyErr) : undefined
const initialData = cacheGet(key) || config.initialData
const initialError = cacheGet(keyErr)

let [state, dispatch] = useReducer<reducerType<Data, Error>>(mergeState, {
data: initialData,
Expand Down Expand Up @@ -540,11 +535,11 @@ function useSWR<Data = any, Error = any>(
}

return {
error: state.error,
// `key` might be changed in the upcoming hook re-render,
// but the previous state will stay
// so we need to match the latest key and data
data: keyRef.current === key ? state.data : undefined,
// so we need to match the latest key and data (fallback to `initialData`)
error: keyRef.current === key ? state.error : initialError,
data: keyRef.current === key ? state.data : initialData,
revalidate, // handler
isValidating: state.isValidating
}
Expand Down