├── .all-contributorsrc
├── .editorconfig
├── .eslintignore
├── .eslintrc.js
├── .github
├── CODEOWNERS
└── workflows
│ └── main.yml
├── .gitignore
├── .npmignore
├── CONTRIBUTING.md
├── LICENSE
├── README.md
├── babel.config.js
├── docs
├── .vitepress
│ ├── cache
│ │ └── deps
│ │ │ ├── @vue_devtools-api.js
│ │ │ ├── _metadata.json
│ │ │ ├── package.json
│ │ │ └── vue.js
│ ├── config.ts
│ └── theme
│ │ ├── index.css
│ │ └── index.ts
├── configuration.md
├── features.md
├── guide.md
├── index.md
├── public
│ ├── apple-touch-icon.png
│ ├── favicon-16x16.png
│ ├── favicon-32x32.png
│ ├── favicon.ico
│ ├── logo_45.png
│ ├── robots.txt
│ └── safari-pinned-tab.svg
└── use-swrv.md
├── examples
├── axios-typescript-nuxt
│ ├── .gitignore
│ ├── .prettierrc
│ ├── README.md
│ ├── nuxt.config.js
│ ├── package.json
│ ├── pages
│ │ └── index.vue
│ ├── plugins
│ │ └── compositionApi.ts
│ ├── tsconfig.json
│ └── yarn.lock
├── basic
│ ├── README.md
│ ├── package.json
│ ├── src
│ │ ├── App.vue
│ │ ├── Repos.vue
│ │ └── main.js
│ └── yarn.lock
├── pwa
│ ├── README.md
│ ├── babel.config.js
│ ├── package.json
│ ├── public
│ │ ├── favicon.ico
│ │ ├── index.html
│ │ └── robots.txt
│ ├── src
│ │ ├── App.vue
│ │ ├── assets
│ │ │ └── logo.png
│ │ ├── components
│ │ │ ├── TodoItem.vue
│ │ │ └── TodosList.vue
│ │ ├── main.js
│ │ ├── registerServiceWorker.js
│ │ └── useTodos.js
│ └── yarn.lock
├── ssr-nuxt
│ ├── Post.vue
│ ├── README.md
│ ├── layouts
│ │ └── default.vue
│ ├── main.css
│ ├── nuxt.config.js
│ ├── package.json
│ ├── pages
│ │ ├── _id.vue
│ │ └── index.vue
│ ├── plugins
│ │ └── vue-composition-api.js
│ └── yarn.lock
└── vite
│ ├── App.vue
│ ├── README.md
│ ├── components
│ └── HelloWorld.vue
│ ├── index.html
│ ├── package.json
│ ├── vite.config.js
│ └── yarn.lock
├── jest.config.js
├── logo.png
├── netlify.toml
├── package.json
├── src
├── cache
│ ├── adapters
│ │ └── localStorage.ts
│ └── index.ts
├── index.ts
├── lib
│ ├── hash.ts
│ └── web-preset.ts
├── types.ts
└── use-swrv.ts
├── tests
├── cache.spec.tsx
├── ssr.spec.ts
├── test-compat-all.sh
├── test-compat.sh
├── use-swrv.spec.tsx
└── utils
│ ├── jest-timeout.ts
│ └── tick.ts
├── tsconfig.build.json
├── tsconfig.json
└── yarn.lock
/.all-contributorsrc:
--------------------------------------------------------------------------------
1 | {
2 | "projectName": "swrv",
3 | "projectOwner": "Kong",
4 | "repoType": "github",
5 | "repoHost": "https://github.com",
6 | "files": [
7 | "README.md"
8 | ],
9 | "imageSize": 100,
10 | "commit": false,
11 | "commitConvention": "none",
12 | "contributors": [
13 | {
14 | "login": "darrenjennings",
15 | "name": "Darren Jennings",
16 | "avatar_url": "https://avatars2.githubusercontent.com/u/5770711?v=4",
17 | "profile": "https://guuu.io/",
18 | "contributions": [
19 | "code",
20 | "doc"
21 | ]
22 | },
23 | {
24 | "login": "Atinux",
25 | "name": "Sébastien Chopin",
26 | "avatar_url": "https://avatars2.githubusercontent.com/u/904724?v=4",
27 | "profile": "https://atinux.com",
28 | "contributions": [
29 | "code",
30 | "ideas"
31 | ]
32 | },
33 | {
34 | "login": "chuca",
35 | "name": "Fernando Machuca",
36 | "avatar_url": "https://avatars0.githubusercontent.com/u/864496?v=4",
37 | "profile": "https://github.com/chuca",
38 | "contributions": [
39 | "design"
40 | ]
41 | },
42 | {
43 | "login": "zeit",
44 | "name": "ZEIT",
45 | "avatar_url": "https://avatars0.githubusercontent.com/u/14985020?v=4",
46 | "profile": "https://zeit.co",
47 | "contributions": [
48 | "ideas"
49 | ]
50 | },
51 | {
52 | "login": "adamdehaven",
53 | "name": "Adam DeHaven",
54 | "avatar_url": "https://avatars.githubusercontent.com/u/2229946?v=4",
55 | "profile": "https://www.adamdehaven.com",
56 | "contributions": [
57 | "code",
58 | "doc",
59 | "maintenance"
60 | ]
61 | }
62 | ],
63 | "contributorsPerLine": 7
64 | }
65 |
--------------------------------------------------------------------------------
/.editorconfig:
--------------------------------------------------------------------------------
1 | [*]
2 | indent_style = space
3 | indent_size = 2
4 | trim_trailing_whitespace = true
5 | insert_final_newline = true
6 |
--------------------------------------------------------------------------------
/.eslintignore:
--------------------------------------------------------------------------------
1 | dist
2 | esm
--------------------------------------------------------------------------------
/.eslintrc.js:
--------------------------------------------------------------------------------
1 | module.exports = {
2 | root: true,
3 | env: {
4 | node: true
5 | },
6 | extends: [
7 | 'plugin:vue/essential',
8 | '@vue/standard',
9 | '@vue/typescript'
10 | ],
11 | rules: {
12 | 'no-console': process.env.NODE_ENV === 'production' ? 'error' : 'off',
13 | 'no-debugger': process.env.NODE_ENV === 'production' ? 'error' : 'off',
14 | 'promise/param-names': 'off',
15 | 'no-multiple-empty-lines': ['error', { max: 1, maxEOF: 1 }],
16 | 'no-trailing-spaces': 'error',
17 | 'eol-last': 'error'
18 | },
19 | parserOptions: {
20 | parser: '@typescript-eslint/parser'
21 | },
22 | overrides: [
23 | {
24 | files: [
25 | '**/__tests__/*.{j,t}s?(x)',
26 | '**/tests/unit/**/*.spec.{j,t}s?(x)'
27 | ],
28 | env: {
29 | jest: true
30 | }
31 | }
32 | ]
33 | }
34 |
--------------------------------------------------------------------------------
/.github/CODEOWNERS:
--------------------------------------------------------------------------------
1 | # CI settings
2 | /.github/ @adamdehaven
3 |
4 | # Deployment settings
5 | /netlify.toml @adamdehaven
6 |
--------------------------------------------------------------------------------
/.github/workflows/main.yml:
--------------------------------------------------------------------------------
1 | name: build
2 |
3 | on:
4 | push:
5 | branches:
6 | - master
7 | - next
8 | pull_request:
9 | branches:
10 | - master
11 | - next
12 |
13 | jobs:
14 | test:
15 | name: Build and Test
16 | runs-on: ubuntu-latest
17 | timeout-minutes: 20
18 | strategy:
19 | matrix:
20 | node-version: [16.x]
21 | steps:
22 | - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2
23 | - name: Use Node.js ${{ matrix.node-version }}
24 | uses: actions/setup-node@1a4442cacd436585916779262731d5b162bc6ec7 # v3.8.2
25 | with:
26 | node-version: ${{ matrix.node-version }}
27 | - name: install, lint
28 | run: |
29 | yarn install --frozen-lockfile
30 | yarn lint --no-fix
31 | - name: tsc
32 | run: |
33 | yarn types:check
34 |
35 | - name: test
36 | run: |
37 | yarn test:compat
38 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | .DS_Store
2 | node_modules
3 | dist
4 |
5 | # local env files
6 | .env.local
7 | .env.*.local
8 |
9 | # Log files
10 | npm-debug.log*
11 | yarn-debug.log*
12 | yarn-error.log*
13 |
14 | # Editor directories and files
15 | .idea
16 | .vscode
17 | *.suo
18 | *.ntvs*
19 | *.njsproj
20 | *.sln
21 | *.sw?
22 |
23 | /esm
24 | /coverage
25 | .nuxt
26 | /docs/.vitepress/cache
27 | .yarn
28 |
--------------------------------------------------------------------------------
/.npmignore:
--------------------------------------------------------------------------------
1 | node_modules
2 | *.log
3 | *.tgz
4 | .env
5 | .next
6 | .DS_Store
7 |
--------------------------------------------------------------------------------
/CONTRIBUTING.md:
--------------------------------------------------------------------------------
1 | # Contributing :monkey_face:
2 |
3 | Hello, and welcome! Whether you are looking for help, trying to report a bug,
4 | thinking about getting involved in the project or about to submit a patch, this
5 | document is for you! Its intent is to be both an entry point for newcomers to
6 | the community (with various technical backgrounds), and a guide/reference for
7 | contributors and maintainers.
8 |
9 | Consult the Table of Contents below, and jump to the desired section.
10 |
11 | - [Development](#development)
12 | - [Code Style](#code-style)
13 | - [Linting](#linting)
14 | - [Running Tests](#running-tests)
15 | - [Verifying the Build Output](#verifying-the-build-output)
16 | - [Deploying](#deploying)
17 |
18 | ## Development
19 |
20 | This project uses the [vue-cli](https://cli.vuejs.org/) for linting, testing,
21 | and building. See package.json for all currently used plugins.
22 |
23 | ### Code Style
24 |
25 | If it passes linting, YOLO. Improvements to ASCII art encouraged.
26 |
27 | ### Linting
28 |
29 | ```sh
30 | # Autofixes any linting issues
31 | yarn lint
32 |
33 | # Outputs linting issues that need to be fixed without fixing
34 | yarn lint --no-fix
35 | ```
36 |
37 | ### Running Tests
38 |
39 | Swrv has a suite of unit tests that are meant to be as comprehensive as
40 | possible. They run in CI and are required to pass in order to merge.
41 |
42 | ```sh
43 | # Run all tests
44 | yarn test
45 |
46 | # Run all tests and watch file changes to trigger a rerun (also enters jest mode to filter tests)
47 | yarn test --watchAll
48 |
49 | # Run just a single test file
50 | yarn test use-swrv
51 | ```
52 |
53 | Tests can get you most of the way there when developing a new feature. However,
54 | you will want to test it in a real app eventually.
55 |
56 | ### Verifying the Build Output
57 |
58 | This could be better experience. If you want to develop swrv and test that the
59 | esm/dist bundles are working correctly, you can run the build command and copy
60 | the bundle to your project.
61 |
62 | ```sh
63 | yarn build
64 | ```
65 |
66 | Output inside `esm`, and `dist` will contain output from `tsc` build. Move this
67 | into your project and change import statements. Using `yarn link` is an exercise
68 | left to the reader. Contributions to this doc are welcome if you get it working!
69 |
70 | ## Deploying
71 |
72 | > Note: this is for maintainers of the repo, with access to publish to NPM
73 |
74 | After merging a PR, you will want to get it up on the registry for everyone to
75 | use.
76 |
77 | 1. bump the version according to [semver](https://semver.org/) in the
78 | package.json of the repo with the appropriate new version `x.x.x`
79 | 1. `git commit` with the message `chore(release) x.x.x` directly to your local
80 | master.
81 | 1. Build the library artifacts `yarn build`
82 | 1. Login as an authorized npm user (has access to swrv npm package)
83 | 1. `npm publish`
84 | 1. Once published, git push to origin/master
85 | 1. draft a github release following the naming conventions of the other
86 | releases.
87 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | Apache License
2 | Version 2.0, January 2004
3 | http://www.apache.org/licenses/
4 |
5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6 |
7 | 1. Definitions.
8 |
9 | "License" shall mean the terms and conditions for use, reproduction,
10 | and distribution as defined by Sections 1 through 9 of this document.
11 |
12 | "Licensor" shall mean the copyright owner or entity authorized by
13 | the copyright owner that is granting the License.
14 |
15 | "Legal Entity" shall mean the union of the acting entity and all
16 | other entities that control, are controlled by, or are under common
17 | control with that entity. For the purposes of this definition,
18 | "control" means (i) the power, direct or indirect, to cause the
19 | direction or management of such entity, whether by contract or
20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the
21 | outstanding shares, or (iii) beneficial ownership of such entity.
22 |
23 | "You" (or "Your") shall mean an individual or Legal Entity
24 | exercising permissions granted by this License.
25 |
26 | "Source" form shall mean the preferred form for making modifications,
27 | including but not limited to software source code, documentation
28 | source, and configuration files.
29 |
30 | "Object" form shall mean any form resulting from mechanical
31 | transformation or translation of a Source form, including but
32 | not limited to compiled object code, generated documentation,
33 | and conversions to other media types.
34 |
35 | "Work" shall mean the work of authorship, whether in Source or
36 | Object form, made available under the License, as indicated by a
37 | copyright notice that is included in or attached to the work
38 | (an example is provided in the Appendix below).
39 |
40 | "Derivative Works" shall mean any work, whether in Source or Object
41 | form, that is based on (or derived from) the Work and for which the
42 | editorial revisions, annotations, elaborations, or other modifications
43 | represent, as a whole, an original work of authorship. For the purposes
44 | of this License, Derivative Works shall not include works that remain
45 | separable from, or merely link (or bind by name) to the interfaces of,
46 | the Work and Derivative Works thereof.
47 |
48 | "Contribution" shall mean any work of authorship, including
49 | the original version of the Work and any modifications or additions
50 | to that Work or Derivative Works thereof, that is intentionally
51 | submitted to Licensor for inclusion in the Work by the copyright owner
52 | or by an individual or Legal Entity authorized to submit on behalf of
53 | the copyright owner. For the purposes of this definition, "submitted"
54 | means any form of electronic, verbal, or written communication sent
55 | to the Licensor or its representatives, including but not limited to
56 | communication on electronic mailing lists, source code control systems,
57 | and issue tracking systems that are managed by, or on behalf of, the
58 | Licensor for the purpose of discussing and improving the Work, but
59 | excluding communication that is conspicuously marked or otherwise
60 | designated in writing by the copyright owner as "Not a Contribution."
61 |
62 | "Contributor" shall mean Licensor and any individual or Legal Entity
63 | on behalf of whom a Contribution has been received by Licensor and
64 | subsequently incorporated within the Work.
65 |
66 | 2. Grant of Copyright License. Subject to the terms and conditions of
67 | this License, each Contributor hereby grants to You a perpetual,
68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69 | copyright license to reproduce, prepare Derivative Works of,
70 | publicly display, publicly perform, sublicense, and distribute the
71 | Work and such Derivative Works in Source or Object form.
72 |
73 | 3. Grant of Patent License. Subject to the terms and conditions of
74 | this License, each Contributor hereby grants to You a perpetual,
75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76 | (except as stated in this section) patent license to make, have made,
77 | use, offer to sell, sell, import, and otherwise transfer the Work,
78 | where such license applies only to those patent claims licensable
79 | by such Contributor that are necessarily infringed by their
80 | Contribution(s) alone or by combination of their Contribution(s)
81 | with the Work to which such Contribution(s) was submitted. If You
82 | institute patent litigation against any entity (including a
83 | cross-claim or counterclaim in a lawsuit) alleging that the Work
84 | or a Contribution incorporated within the Work constitutes direct
85 | or contributory patent infringement, then any patent licenses
86 | granted to You under this License for that Work shall terminate
87 | as of the date such litigation is filed.
88 |
89 | 4. Redistribution. You may reproduce and distribute copies of the
90 | Work or Derivative Works thereof in any medium, with or without
91 | modifications, and in Source or Object form, provided that You
92 | meet the following conditions:
93 |
94 | (a) You must give any other recipients of the Work or
95 | Derivative Works a copy of this License; and
96 |
97 | (b) You must cause any modified files to carry prominent notices
98 | stating that You changed the files; and
99 |
100 | (c) You must retain, in the Source form of any Derivative Works
101 | that You distribute, all copyright, patent, trademark, and
102 | attribution notices from the Source form of the Work,
103 | excluding those notices that do not pertain to any part of
104 | the Derivative Works; and
105 |
106 | (d) If the Work includes a "NOTICE" text file as part of its
107 | distribution, then any Derivative Works that You distribute must
108 | include a readable copy of the attribution notices contained
109 | within such NOTICE file, excluding those notices that do not
110 | pertain to any part of the Derivative Works, in at least one
111 | of the following places: within a NOTICE text file distributed
112 | as part of the Derivative Works; within the Source form or
113 | documentation, if provided along with the Derivative Works; or,
114 | within a display generated by the Derivative Works, if and
115 | wherever such third-party notices normally appear. The contents
116 | of the NOTICE file are for informational purposes only and
117 | do not modify the License. You may add Your own attribution
118 | notices within Derivative Works that You distribute, alongside
119 | or as an addendum to the NOTICE text from the Work, provided
120 | that such additional attribution notices cannot be construed
121 | as modifying the License.
122 |
123 | You may add Your own copyright statement to Your modifications and
124 | may provide additional or different license terms and conditions
125 | for use, reproduction, or distribution of Your modifications, or
126 | for any such Derivative Works as a whole, provided Your use,
127 | reproduction, and distribution of the Work otherwise complies with
128 | the conditions stated in this License.
129 |
130 | 5. Submission of Contributions. Unless You explicitly state otherwise,
131 | any Contribution intentionally submitted for inclusion in the Work
132 | by You to the Licensor shall be under the terms and conditions of
133 | this License, without any additional terms or conditions.
134 | Notwithstanding the above, nothing herein shall supersede or modify
135 | the terms of any separate license agreement you may have executed
136 | with Licensor regarding such Contributions.
137 |
138 | 6. Trademarks. This License does not grant permission to use the trade
139 | names, trademarks, service marks, or product names of the Licensor,
140 | except as required for reasonable and customary use in describing the
141 | origin of the Work and reproducing the content of the NOTICE file.
142 |
143 | 7. Disclaimer of Warranty. Unless required by applicable law or
144 | agreed to in writing, Licensor provides the Work (and each
145 | Contributor provides its Contributions) on an "AS IS" BASIS,
146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147 | implied, including, without limitation, any warranties or conditions
148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149 | PARTICULAR PURPOSE. You are solely responsible for determining the
150 | appropriateness of using or redistributing the Work and assume any
151 | risks associated with Your exercise of permissions under this License.
152 |
153 | 8. Limitation of Liability. In no event and under no legal theory,
154 | whether in tort (including negligence), contract, or otherwise,
155 | unless required by applicable law (such as deliberate and grossly
156 | negligent acts) or agreed to in writing, shall any Contributor be
157 | liable to You for damages, including any direct, indirect, special,
158 | incidental, or consequential damages of any character arising as a
159 | result of this License or out of the use or inability to use the
160 | Work (including but not limited to damages for loss of goodwill,
161 | work stoppage, computer failure or malfunction, or any and all
162 | other commercial damages or losses), even if such Contributor
163 | has been advised of the possibility of such damages.
164 |
165 | 9. Accepting Warranty or Additional Liability. While redistributing
166 | the Work or Derivative Works thereof, You may choose to offer,
167 | and charge a fee for, acceptance of support, warranty, indemnity,
168 | or other liability obligations and/or rights consistent with this
169 | License. However, in accepting such obligations, You may act only
170 | on Your own behalf and on Your sole responsibility, not on behalf
171 | of any other Contributor, and only if You agree to indemnify,
172 | defend, and hold each Contributor harmless for any liability
173 | incurred by, or claims asserted against, such Contributor by reason
174 | of your accepting any such warranty or additional liability.
175 |
176 | END OF TERMS AND CONDITIONS
177 |
178 | APPENDIX: How to apply the Apache License to your work.
179 |
180 | To apply the Apache License to your work, attach the following
181 | boilerplate notice, with the fields enclosed by brackets "{}"
182 | replaced with your own identifying information. (Don't include
183 | the brackets!) The text should be enclosed in the appropriate
184 | comment syntax for the file format. We also recommend that a
185 | file or class name and description of purpose be included on the
186 | same "printed page" as the copyright notice for easier
187 | identification within third-party archives.
188 |
189 | Copyright 2020 Kong Inc.
190 |
191 | Licensed under the Apache License, Version 2.0 (the "License");
192 | you may not use this file except in compliance with the License.
193 | You may obtain a copy of the License at
194 |
195 | http://www.apache.org/licenses/LICENSE-2.0
196 |
197 | Unless required by applicable law or agreed to in writing, software
198 | distributed under the License is distributed on an "AS IS" BASIS,
199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200 | See the License for the specific language governing permissions and
201 | limitations under the License.
202 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
swrv
5 |
6 | [](https://www.npmjs.com/package/swrv) [](https://www.npmjs.com/package/swrv) 
7 |
8 | `swrv` (pronounced "swerve") is a library using the [Vue Composition API](https://vuejs.org/guide/extras/composition-api-faq.html) for remote data fetching. It is largely a port of [swr](https://github.com/zeit/swr).
9 |
10 | - [Documentation](https://docs-swrv.netlify.app/)
11 |
12 | The name “SWR” is derived from stale-while-revalidate, a cache invalidation strategy popularized by HTTP [RFC 5861](https://tools.ietf.org/html/rfc5861). SWR first returns the data from cache (stale), then sends the fetch request (revalidate), and finally comes with the up-to-date data again.
13 |
14 | Features:
15 |
16 | - Transport and protocol agnostic data fetching
17 | - Fast page navigation
18 | - Interval polling
19 | - ~~SSR support~~ (removed as of version `0.10.0` - [read more](https://github.com/Kong/swrv/pull/304))
20 | - Vue 3 Support
21 | - Revalidation on focus
22 | - Request deduplication
23 | - TypeScript ready
24 | - Minimal API
25 | - Stale-if-error
26 | - Customizable cache implementation
27 | - Error Retry
28 |
29 | With `swrv`, components will get a stream of data updates constantly and automatically. Thus, the UI will be always fast and reactive.
30 |
31 | ## Table of Contents
32 |
33 | - [Installation](#installation)
34 | - [Vue 3](#vue-3)
35 | - [Vue 2.7](#vue-27)
36 | - [Vue 2.6 and below](#vue-26-and-below)
37 | - [Getting Started](#getting-started)
38 | - [Api](#api)
39 | - [Parameters](#parameters)
40 | - [Return Values](#return-values)
41 | - [Config options](#config-options)
42 | - [Prefetching](#prefetching)
43 | - [Dependent Fetching](#dependent-fetching)
44 | - [Stale-if-error](#stale-if-error)
45 | - [State Management](#state-management)
46 | - [useSwrvState](#useswrvstate)
47 | - [Vuex](#vuex)
48 | - [Cache](#cache)
49 | - [localStorage](#localstorage)
50 | - [Serve from cache only](#serve-from-cache-only)
51 | - [Error Handling](#error-handling)
52 | - [FAQ](#faq)
53 | - [How is swrv different from the swr react library](#how-is-swrv-different-from-the-swr-react-library)
54 | - [Why does swrv make so many requests](#why-does-swrv-make-so-many-requests)
55 | - [How can I refetch swrv data to update it](#how-can-i-refetch-swrv-data-to-update-it)
56 | - [Contributors ✨](#contributors-)
57 |
58 | ## Installation
59 |
60 | The version of `swrv` you install depends on the Vue dependency in your project.
61 |
62 | ### Vue 3
63 |
64 | ```shell
65 | # Install the latest version
66 | yarn add swrv
67 | ```
68 |
69 | ### Vue 2.7
70 |
71 | This version removes the dependency of the external `@vue/composition-api` plugin and adds `vue` to the `peerDependencies`, requiring a version that matches the following pattern: `>= 2.7.0 < 3`
72 |
73 | ```shell
74 | # Install the 0.10.x version for Vue 2.7
75 | yarn add swrv@v2-latest
76 | ```
77 |
78 | ### Vue 2.6 and below
79 |
80 | If you're installing for Vue `2.6.x` and below, you may want to check out a [previous version of the README](https://github.com/Kong/swrv/blob/b621aac02b7780a4143c5743682070223e793b10/README.md) to view how to initialize `swrv` utilizing the external `@vue/composition-api` plugin.
81 |
82 | ```shell
83 | # Install the 0.9.x version for Vue < 2.7
84 | yarn add swrv@legacy
85 | ```
86 |
87 | ## Getting Started
88 |
89 | ```vue
90 |
91 |
92 |
failed to load
93 |
loading...
94 |
hello {{ data.name }}
95 |
96 |
97 |
98 |
114 | ```
115 |
116 | In this example, the Vue Hook `useSWRV` accepts a `key` and a `fetcher` function. `key` is a unique identifier of the request, normally the URL of the API. And the fetcher accepts key as its parameter and returns the data asynchronously.
117 |
118 | `useSWRV` also returns 2 values: `data` and `error`. When the request (fetcher) is not yet finished, data will be `undefined`. And when we get a response, it sets `data` and `error` based on the result of fetcher and rerenders the component. This is because `data` and `error` are Vue [Refs](https://vuejs.org/api/reactivity-core.html#ref), and their values will be set by the fetcher response.
119 |
120 | Note that fetcher can be any asynchronous function, so you can use your favorite data-fetching library to handle that part. When omitted, swrv falls back to the browser [Fetch API](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API).
121 |
122 | ## Api
123 |
124 | ```ts
125 | const { data, error, isValidating, mutate } = useSWRV(key, fetcher, options)
126 | ```
127 |
128 | ### Parameters
129 |
130 | | Param | Required | Description |
131 | | --------- | -------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
132 | | `key` | yes | a unique key string for the request (or a reactive reference / watcher function / null) (advanced usage) |
133 | | `fetcher` | | a Promise returning function to fetch your data. If `null`, swrv will fetch from cache only and not revalidate. If omitted (i.e. `undefined`) then the [fetch](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API) api will be used. |
134 | | `options` | | an object of configuration options |
135 |
136 | ### Return Values
137 |
138 | - `data`: data for the given key resolved by fetcher (or undefined if not
139 | loaded)
140 | - `error`: error thrown by fetcher (or undefined)
141 | - `isValidating`: if there's a request or revalidation loading
142 | - `mutate`: function to trigger the validation manually
143 |
144 | ### Config options
145 |
146 | See [Config Defaults](https://github.com/Kong/swrv/blob/1587416e59dad12f9261e289b8cf63da81aa2dd4/src/use-swrv.ts#L43)
147 |
148 | - `refreshInterval = 0` - polling interval in milliseconds. 0 means this is
149 | disabled.
150 | - `dedupingInterval = 2000` - dedupe requests with the same key in this time
151 | span
152 | - `ttl = 0` - time to live of response data in cache. 0 mean it stays around
153 | forever.
154 | - `shouldRetryOnError = true` - retry when fetcher has an error
155 | - `errorRetryInterval = 5000` - error retry interval
156 | - `errorRetryCount: 5` - max error retry count
157 | - `revalidateOnFocus = true` - auto revalidate when window gets focused
158 | - `revalidateDebounce = 0` - debounce in milliseconds for revalidation. Useful
159 | for when a component is serving from the cache immediately, but then un-mounts
160 | soon thereafter (e.g. a user clicking "next" in pagination quickly) to avoid
161 | unnecessary fetches.
162 | - `cache` - caching instance to store response data in. See
163 | [src/lib/cache](src/lib/cache.ts), and [Cache](#cache) below.
164 |
165 | ## Prefetching
166 |
167 | Prefetching can be useful for when you anticipate user actions, like hovering over a link. SWRV exposes the `mutate` function so that results can be stored in the SWRV cache at a predetermined time.
168 |
169 | ```ts
170 | import { mutate } from 'swrv'
171 |
172 | function prefetch() {
173 | mutate(
174 | '/api/data',
175 | fetch('/api/data').then((res) => res.json())
176 | )
177 | // the second parameter is a Promise
178 | // SWRV will use the result when it resolves
179 | }
180 | ```
181 |
182 | ## Dependent Fetching
183 |
184 | swrv also allows you to fetch data that depends on other data. It ensures the maximum possible parallelism (avoiding waterfalls), as well as serial fetching when a piece of dynamic data is required for the next data fetch to happen.
185 |
186 | ```vue
187 |
188 |
loading...
189 |
You have {{ projects.length }} projects
190 |
191 |
192 |
214 | ```
215 |
216 | ## Stale-if-error
217 |
218 | One of the benefits of a stale content caching strategy is that the cache can be served when requests fail.`swrv` uses a [stale-if-error](https://tools.ietf.org/html/rfc5861#section-4) strategy and will maintain `data` in the cache even if a `useSWRV` fetch returns an `error`.
219 |
220 | ```vue
221 |
222 |
failed to load
223 |
loading...
224 |
225 | hello {{ data.name }} of {{ data.birthplace }}. This content will continue
226 | to appear even if future requests to {{ endpoint }} fail!
227 |
228 |
229 |
230 |
249 | ```
250 |
251 | ## State Management
252 |
253 | ### useSwrvState
254 |
255 | Sometimes you might want to know the exact state where swrv is during stale-while-revalidate lifecyle. This is helpful when representing the UI as a function of state. Here is one way to detect state using a user-land composable `useSwrvState` function:
256 |
257 | ```js
258 | import { ref, watchEffect } from 'vue'
259 |
260 | const STATES = {
261 | VALIDATING: 'VALIDATING',
262 | PENDING: 'PENDING',
263 | SUCCESS: 'SUCCESS',
264 | ERROR: 'ERROR',
265 | STALE_IF_ERROR: 'STALE_IF_ERROR',
266 | }
267 |
268 | export default function(data, error, isValidating) {
269 | const state = ref('idle')
270 | watchEffect(() => {
271 | if (data.value && isValidating.value) {
272 | state.value = STATES.VALIDATING
273 | return
274 | }
275 | if (data.value && error.value) {
276 | state.value = STATES.STALE_IF_ERROR
277 | return
278 | }
279 | if (data.value === undefined && !error.value) {
280 | state.value = STATES.PENDING
281 | return
282 | }
283 | if (data.value && !error.value) {
284 | state.value = STATES.SUCCESS
285 | return
286 | }
287 | if (data.value === undefined && error) {
288 | state.value = STATES.ERROR
289 | return
290 | }
291 | })
292 |
293 | return {
294 | state,
295 | STATES,
296 | }
297 | }
298 | ```
299 |
300 | And then in your template you can use it like so:
301 |
302 | ```vue
303 |
304 |
305 |
306 | {{ error }}
307 |
308 |
Loading...
309 |
310 |
311 |
312 |
319 | {{ data }}
320 |
321 |
322 |
323 |
324 |
350 | ```
351 |
352 | ### Vuex
353 |
354 | Most of the features of swrv handle the complex logic / ceremony that you'd have to implement yourself inside a vuex store. All swrv instances use the same global cache, so if you are using swrv alongside vuex, you can use global watchers on resolved swrv returned refs. It is encouraged to wrap useSWRV in a custom composable function so that you can do application level side effects if desired (e.g. dispatch a vuex action when data changes to log events or perform some logic).
355 |
356 | Vue 3 example:
357 |
358 | ```vue
359 |
391 | ```
392 |
393 | ## Cache
394 |
395 | By default, a custom cache implementation is used to store fetcher response data cache, in-flight promise cache, and ref cache. Response data cache can be customized via the `config.cache` property. Built in cache adapters:
396 |
397 | ### localStorage
398 |
399 | A common usage case to have a better _offline_ experience is to read from `localStorage`. Checkout the [PWA example](https://github.com/Kong/swrv/tree/master/examples/pwa) for more inspiration.
400 |
401 | ```ts
402 | import useSWRV from 'swrv'
403 | import LocalStorageCache from 'swrv/dist/cache/adapters/localStorage'
404 |
405 | function useTodos () {
406 | const { data, error } = useSWRV('/todos', undefined, {
407 | cache: new LocalStorageCache('swrv'),
408 | shouldRetryOnError: false
409 | })
410 |
411 | return {
412 | data,
413 | error
414 | }
415 | }
416 | ```
417 |
418 | ### Serve from cache only
419 |
420 | To only retrieve a swrv cache response without revalidating, you can set the fetcher function to `null` from the useSWRV call. This can be useful when there is some higher level swrv composable that is always sending data to other instances, so you can assume that composables with a `null` fetcher will have data available. This [isn't very intuitive](https://github.com/Kong/swrv/issues/148), so will be looking for ways to improve this api in the future.
421 |
422 | ```ts
423 | // Component A
424 | const { data } = useSWRV('/api/config', fetcher)
425 |
426 | // Component B, only retrieve from cache
427 | const { data } = useSWRV('/api/config', null)
428 | ```
429 |
430 | ## Error Handling
431 |
432 | Since `error` is returned as a Vue Ref, you can use watchers to handle any onError callback functionality. Check out [the test](https://github.com/Kong/swrv/blob/a063c4aa142a5a13dbd39496cefab7aef54e610c/tests/use-swrv.spec.tsx#L481).
433 |
434 | ```ts
435 | export default {
436 | setup() {
437 | const { data, error } = useSWRV(key, fetch)
438 |
439 | function handleError(error) {
440 | console.error(error && error.message)
441 | }
442 |
443 | watch(error, handleError)
444 |
445 | return {
446 | data,
447 | error,
448 | }
449 | },
450 | }
451 | ```
452 |
453 | ## FAQ
454 |
455 | ### How is swrv different from the [swr](https://github.com/zeit/swr) react library
456 |
457 | #### Vue and Reactivity
458 |
459 | The `swrv` library is meant to be used with the Vue Composition API (and eventually Vue 3) so it utilizes Vue's reactivity system to track dependencies and returns vue `Ref`'s as it's return values. This allows you to watch `data` or build your own computed props. For example, the key function is implemented as Vue `watch`er, so any changes to the dependencies in this function will trigger a revalidation in `swrv`.
460 |
461 | #### Features
462 |
463 | Features were built as needed for `swrv`, and while the initial development of `swrv` was mostly a port of swr, the feature sets are not 1-1, and are subject to diverge as they already have.
464 |
465 | ### Why does swrv make so many requests
466 |
467 | The idea behind stale-while-revalidate is that you always get fresh data eventually. You can disable some of the eager fetching such as `config.revalidateOnFocus`, but it is preferred to serve a fast response from cache while also revalidating so users are always getting the most up to date data.
468 |
469 | ### How can I refetch swrv data to update it
470 |
471 | Swrv fetcher functions can be triggered on-demand by using the `mutate` [return value](https://github.com/Kong/swrv/#return-values). This is useful when there is some event that needs to trigger a revalidation such a PATCH request that updates the initial GET request response data.
472 |
473 | ## Contributors ✨
474 |
475 | Thanks goes to these wonderful people ([emoji key](https://allcontributors.org/docs/en/emoji-key)):
476 |
477 |
478 |
479 |
480 |
32 |
33 |
34 |
56 | ```
57 |
58 | ## Stale-if-error
59 |
60 | One of the benefits of a stale content caching strategy is that the cache can be served when requests fail.`swrv` uses a [stale-if-error](https://tools.ietf.org/html/rfc5861#section-4) strategy and will maintain `data` in the cache even if a `useSWRV` fetch returns an `error`.
61 |
62 | ```vue
63 |
64 |
failed to load
65 |
loading...
66 |
67 | hello {{ data.name }} of {{ data.birthplace }}. This content will continue
68 | to appear even if future requests to {{ endpoint }} fail!
69 |
70 |
71 |
72 |
91 | ```
92 |
93 | ## State Management
94 |
95 | ### useSwrvState
96 |
97 | Sometimes you might want to know the exact state where swrv is during stale-while-revalidate lifecyle. This is helpful when representing the UI as a function of state. Here is one way to detect state using a user-land composable `useSwrvState` function:
98 |
99 | ```js
100 | import { ref, watchEffect } from 'vue'
101 |
102 | const STATES = {
103 | VALIDATING: 'VALIDATING',
104 | PENDING: 'PENDING',
105 | SUCCESS: 'SUCCESS',
106 | ERROR: 'ERROR',
107 | STALE_IF_ERROR: 'STALE_IF_ERROR',
108 | }
109 |
110 | export default function(data, error, isValidating) {
111 | const state = ref('idle')
112 | watchEffect(() => {
113 | if (data.value && isValidating.value) {
114 | state.value = STATES.VALIDATING
115 | return
116 | }
117 | if (data.value && error.value) {
118 | state.value = STATES.STALE_IF_ERROR
119 | return
120 | }
121 | if (data.value === undefined && !error.value) {
122 | state.value = STATES.PENDING
123 | return
124 | }
125 | if (data.value && !error.value) {
126 | state.value = STATES.SUCCESS
127 | return
128 | }
129 | if (data.value === undefined && error) {
130 | state.value = STATES.ERROR
131 | return
132 | }
133 | })
134 |
135 | return {
136 | state,
137 | STATES,
138 | }
139 | }
140 | ```
141 |
142 | And then in your template you can use it like so:
143 |
144 | ```vue
145 |
146 |
147 |
148 | {{ error }}
149 |
150 |
Loading...
151 |
152 |
153 |
154 |
155 | {{ data }}
156 |
157 |
158 |
159 |
160 |
186 | ```
187 |
188 | ### Vuex
189 |
190 | Most of the features of swrv handle the complex logic / ceremony that you'd have to implement yourself inside a vuex store. All swrv instances use the same global cache, so if you are using swrv alongside vuex, you can use global watchers on resolved swrv returned refs. It is encouraged to wrap useSWRV in a custom composable function so that you can do application level side effects if desired (e.g. dispatch a vuex action when data changes to log events or perform some logic).
191 |
192 | Vue 3 example
193 |
194 | ```vue
195 |
227 | ```
228 |
229 | ## Error Handling
230 |
231 | Since `error` is returned as a Vue Ref, you can use watchers to handle any onError callback functionality. Check out [the test](https://github.com/Kong/swrv/blob/a063c4aa142a5a13dbd39496cefab7aef54e610c/tests/use-swrv.spec.tsx#L481).
232 |
233 | ```ts
234 | export default {
235 | setup() {
236 | const { data, error } = useSWRV(key, fetch)
237 |
238 | function handleError(error) {
239 | console.error(error && error.message)
240 | }
241 |
242 | watch(error, handleError)
243 |
244 | return {
245 | data,
246 | error,
247 | }
248 | },
249 | }
250 | ```
251 |
252 | ## Cache
253 |
254 | By default, a custom cache implementation is used to store fetcher response data cache, in-flight promise cache, and ref cache. Response data cache can be customized via the `config.cache` property. Built in cache adapters:
255 |
256 | ### localStorage
257 |
258 | A common usage case to have a better _offline_ experience is to read from `localStorage`. Checkout the [PWA example](https://github.com/Kong/swrv/tree/master/examples/pwa) for more inspiration.
259 |
260 | ```ts
261 | import useSWRV from 'swrv'
262 | import LocalStorageCache from 'swrv/dist/cache/adapters/localStorage'
263 |
264 | function useTodos () {
265 | const { data, error } = useSWRV('/todos', undefined, {
266 | cache: new LocalStorageCache('swrv'),
267 | shouldRetryOnError: false
268 | })
269 |
270 | return {
271 | data,
272 | error
273 | }
274 | }
275 | ```
276 |
277 | ### Serve from cache only
278 |
279 | To only retrieve a swrv cache response without revalidating, you can set the fetcher function to `null` from the useSWRV call. This can be useful when there is some higher level swrv composable that is always sending data to other instances, so you can assume that composables with a `null` fetcher will have data available. This [isn't very intuitive](https://github.com/Kong/swrv/issues/148), so will be looking for ways to improve this api in the future.
280 |
281 | ```ts
282 | // Component A
283 | const { data } = useSWRV('/api/config', fetcher)
284 |
285 | // Component B, only retrieve from cache
286 | const { data } = useSWRV('/api/config', null)
287 | ```
288 |
--------------------------------------------------------------------------------
/docs/guide.md:
--------------------------------------------------------------------------------
1 | ---
2 | title: Getting Started
3 | ---
4 |
5 | # {{ $frontmatter.title }}
6 |
7 | | Version | Downloads | Build |
8 | | --------- | -------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
9 | | [](https://www.npmjs.com/package/swrv) | [](https://www.npmjs.com/package/swrv) | [](https://github.com/Kong/swrv) |
10 |
11 | ## Overview
12 |
13 | `swrv` (pronounced "swerve") is a library using [Vue Composition API](https://vuejs.org/guide/extras/composition-api-faq.html) hooks for remote data fetching. It is largely a port of [swr](https://github.com/zeit/swr).
14 |
15 | The name “SWR” is derived from stale-while-revalidate, a cache invalidation strategy popularized by HTTP [RFC 5861](https://tools.ietf.org/html/rfc5861). SWR first returns the data from cache (stale), then sends the fetch request (revalidate), and finally comes with the up-to-date data again.
16 |
17 | ## Features
18 |
19 | - 📡 Transport and protocol agnostic data fetching
20 | - ⚡️ Fast page navigation
21 | - ⏲ Interval polling
22 | - ~~🖥 SSR support~~ (removed as of version `0.10.0` - [read more](https://github.com/Kong/swrv/pull/304))
23 | - 🖖 Vue 3 Support
24 | - 🖖 Vue 2.7.x Support (under the `v2-latest` tag on npm)
25 | - 🖖 Vue <= 2.6.x Support (under the `legacy` tag on npm)
26 | - Revalidation on focus
27 | - Request deduplication
28 | - TypeScript ready
29 | - Minimal API
30 | - Stale-if-error
31 | - Customizable cache implementation
32 | - Error Retry
33 |
34 | With `swrv`, components will get a stream of data updates constantly and automatically. Thus, the UI will be always fast and reactive.
35 |
36 | ## Installation
37 |
38 | The version of `swrv` you install depends on the Vue dependency in your project.
39 |
40 | ### Vue 3
41 |
42 | ```shell
43 | # Install the latest version
44 | yarn add swrv
45 | ```
46 |
47 | ### Vue 2.7
48 |
49 | This version removes the dependency of the external `@vue/composition-api` plugin and adds `vue` to the `peerDependencies`, requiring a version that matches the following pattern: `>= 2.7.0 < 3`
50 |
51 | ```shell
52 | # Install the 0.10.x version for Vue 2.7
53 | yarn add swrv@v2-latest
54 | ```
55 |
56 | ### Vue 2.6 and below
57 |
58 | If you're installing for Vue `2.6.x` and below, you may want to check out a [previous version of the README](https://github.com/Kong/swrv/blob/b621aac02b7780a4143c5743682070223e793b10/README.md) to view how to initialize `swrv` utilizing the external `@vue/composition-api` plugin.
59 |
60 | ```shell
61 | # Install the 0.9.x version for Vue < 2.7
62 | yarn add swrv@legacy
63 | ```
64 |
65 | ## Usage
66 |
67 | ```vue
68 |
69 |
70 |
failed to load
71 |
loading...
72 |
hello {{ data.name }}
73 |
74 |
75 |
76 |
90 | ```
91 |
92 | In this example, the Vue Hook `useSWRV` accepts a `key` and a `fetcher` function. `key` is a unique identifier of the request, normally the URL of the API. And the fetcher accepts key as its parameter and returns the data asynchronously.
93 |
94 | `useSWRV` also returns 2 values: `data` and `error`. When the request (fetcher) is not yet finished, data will be `undefined`. And when we get a response, it sets `data` and `error` based on the result of fetcher and rerenders the component. This is because `data` and `error` are Vue [Refs](https://vuejs.org/api/reactivity-core.html#ref), and their values will be set by the fetcher response.
95 |
96 | Note that fetcher can be any asynchronous function, so you can use your favorite data-fetching library to handle that part. When omitted, swrv falls back to the browser [Fetch API](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API).
97 |
--------------------------------------------------------------------------------
/docs/index.md:
--------------------------------------------------------------------------------
1 | ---
2 | layout: home
3 |
4 | hero:
5 | name: swrv
6 | text: A Vue library for data fetching
7 | tagline: With swrv, components will get a stream of data updates constantly and automatically. The UI will always be fast and reactive.
8 | image:
9 | src: /logo_45.png
10 | alt: swrv logo
11 | actions:
12 | - theme: brand
13 | text: Get Started
14 | link: /guide
15 | - theme: alt
16 | text: View on GitHub
17 | link: https://github.com/Kong/swrv
18 |
19 | features:
20 | - title: Feature-rich Data Fetching
21 | details: Transport and protocol agnostic data fetching, revalidation on focus,
22 | polling, in-flight de-duplication.
23 | - title: Vue Composition API
24 | details: Start developing with power of Vue 3, using the reactivity system of the Vue Composition API.
25 | - title: Stale-while-revalidate
26 | details: Uses cache to serve pages fast, while revalidating data sources producing an eventually consistent UI.
27 | ---
28 |
--------------------------------------------------------------------------------
/docs/public/apple-touch-icon.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Kong/swrv/790a22cff70218c69020b1ef434e01cd3ec3ac5c/docs/public/apple-touch-icon.png
--------------------------------------------------------------------------------
/docs/public/favicon-16x16.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Kong/swrv/790a22cff70218c69020b1ef434e01cd3ec3ac5c/docs/public/favicon-16x16.png
--------------------------------------------------------------------------------
/docs/public/favicon-32x32.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Kong/swrv/790a22cff70218c69020b1ef434e01cd3ec3ac5c/docs/public/favicon-32x32.png
--------------------------------------------------------------------------------
/docs/public/favicon.ico:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Kong/swrv/790a22cff70218c69020b1ef434e01cd3ec3ac5c/docs/public/favicon.ico
--------------------------------------------------------------------------------
/docs/public/logo_45.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Kong/swrv/790a22cff70218c69020b1ef434e01cd3ec3ac5c/docs/public/logo_45.png
--------------------------------------------------------------------------------
/docs/public/robots.txt:
--------------------------------------------------------------------------------
1 | User-agent: *
2 | Disallow: /configuration.html
3 |
--------------------------------------------------------------------------------
/docs/public/safari-pinned-tab.svg:
--------------------------------------------------------------------------------
1 |
2 |
4 |
33 |
--------------------------------------------------------------------------------
/docs/use-swrv.md:
--------------------------------------------------------------------------------
1 | ---
2 | title: useSWRV
3 | ---
4 |
5 | # {{ $frontmatter.title }} {#useSWRV}
6 |
7 | ```ts
8 | const {
9 | data, error, isValidating, isLoading, mutate
10 | } = useSWRV(key, fetcher, options)
11 | ```
12 |
13 | ## Parameters
14 |
15 | ### `key`
16 |
17 | - **Type**: `IKey`
18 | - **Required**: true
19 |
20 | ```ts
21 | type IKey =
22 | | string
23 | | any[]
24 | | null
25 | | undefined
26 | | WatchSource
27 | ```
28 |
29 | A unique identifier for the request. This can be:
30 |
31 | - A string
32 | - An array (e.g., `[query, page]`), which gets hashed internally to produce a unique key
33 | - `null` or `undefined`, which disables fetching
34 | - A reactive reference or getter function returning one of the above types (string, array, `null`, or `undefined`)
35 |
36 | ### `fetcher`
37 |
38 | - **Type**: `(...args: any) => Data | Promise`
39 |
40 | A `Promise` returning function to fetch your data. If `null`, swrv will fetch from cache only and not revalidate. If omitted (i.e. `undefined`) then the fetch api will be used.
41 |
42 | If the resolved `key` value is an array, the fetcher function will be called with each element of the array as an argument. Otherwise, the fetcher function will be called with the resolved `key` value as the first argument.
43 |
44 | ### `options`
45 |
46 | - **Type**: `IConfig`
47 |
48 | An object of configuration options. See [Config options](#config-options).
49 |
50 | ## Return Values
51 |
52 | ### `data`
53 |
54 | - **Type**: `Ref`
55 |
56 | Data for the given key resolved by fetcher (or `undefined` if not loaded).
57 |
58 | ### `error`
59 |
60 | - **Type**: `Ref`
61 |
62 | Error thrown by fetcher (or `undefined`).
63 |
64 | ### `isValidating`
65 |
66 | - **Type**: `Ref`
67 |
68 | Becomes `true` whenever there is an ongoing request **whether the data is loaded or not**.
69 |
70 | ### `isLoading`
71 |
72 | - **Type**: `Ref`
73 |
74 | Becomes `true` when there is an ongoing request and **data is not loaded yet**.
75 |
76 | ### `mutate`
77 |
78 | - **Type**: `(data?: Data, options?: RevalidateOptions) => void`
79 |
80 | Function to trigger the validation manually. If `data` is provided, it will update the cache with the provided data.
81 |
82 | ```ts
83 | type Data =
84 | | (() => Promise | any)
85 | | Promise
86 | | any
87 |
88 | interface RevalidateOptions {
89 | shouldRetryOnError?: boolean,
90 | errorRetryCount?: number
91 | }
92 | ```
93 |
94 | ## Config options
95 |
96 | See [Config Defaults](https://github.com/Kong/swrv/blob/1587416e59dad12f9261e289b8cf63da81aa2dd4/src/use-swrv.ts#L43)
97 |
98 | ### `refreshInterval`
99 |
100 | - **Type**: `number`
101 | - **Default**: `0`
102 |
103 | Polling interval in milliseconds. `0` means this is disabled.
104 |
105 | ### `dedupingInterval`
106 |
107 | - **Type**: `number`
108 | - **Default**: `2000`
109 |
110 | Dedupe requests with the same key in this time span.
111 |
112 | ### `ttl`
113 |
114 | - **Type**: `number`
115 | - **Default**: `0`
116 |
117 | Time to live of response data in cache. `0` means it stays around forever.
118 |
119 | ### `shouldRetryOnError`
120 |
121 | - **Type**: `boolean`
122 | - **Default**: `true`
123 |
124 | Retry when fetcher has an error.
125 |
126 | ### `errorRetryInterval`
127 |
128 | - **Type**: `number`
129 | - **Default**: `5000`
130 |
131 | Error retry interval.
132 |
133 | ### `errorRetryCount`
134 |
135 | - **Type**: `number`
136 | - **Default**: `5`
137 |
138 | Max error retry count.
139 |
140 | ### `revalidateOnFocus`
141 |
142 | - **Type**: `boolean`
143 | - **Default**: `true`
144 |
145 | Auto-revalidate when window gets focused.
146 |
147 | ### `revalidateDebounce`
148 |
149 | - **Type**: `number`
150 | - **Default**: `0`
151 |
152 | Debounce in milliseconds for revalidation.
153 |
154 | Useful for when a component is serving from the cache immediately, but then un-mounts soon thereafter (e.g. a user clicking "next" in pagination quickly) to avoid unnecessary fetches.
155 |
156 | ### `cache`
157 |
158 | Caching instance to store response data in. See [src/lib/cache](src/lib/cache.ts), and the [Cache](/features#cache) section.
159 |
--------------------------------------------------------------------------------
/examples/axios-typescript-nuxt/.gitignore:
--------------------------------------------------------------------------------
1 | # Created by .ignore support plugin (hsz.mobi)
2 | ### Node template
3 | # Logs
4 | /logs
5 | *.log
6 | npm-debug.log*
7 | yarn-debug.log*
8 | yarn-error.log*
9 |
10 | # Runtime data
11 | pids
12 | *.pid
13 | *.seed
14 | *.pid.lock
15 |
16 | # Directory for instrumented libs generated by jscoverage/JSCover
17 | lib-cov
18 |
19 | # Coverage directory used by tools like istanbul
20 | coverage
21 |
22 | # nyc test coverage
23 | .nyc_output
24 |
25 | # Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files)
26 | .grunt
27 |
28 | # Bower dependency directory (https://bower.io/)
29 | bower_components
30 |
31 | # node-waf configuration
32 | .lock-wscript
33 |
34 | # Compiled binary addons (https://nodejs.org/api/addons.html)
35 | build/Release
36 |
37 | # Dependency directories
38 | node_modules/
39 | jspm_packages/
40 |
41 | # TypeScript v1 declaration files
42 | typings/
43 |
44 | # Optional npm cache directory
45 | .npm
46 |
47 | # Optional eslint cache
48 | .eslintcache
49 |
50 | # Optional REPL history
51 | .node_repl_history
52 |
53 | # Output of 'npm pack'
54 | *.tgz
55 |
56 | # Yarn Integrity file
57 | .yarn-integrity
58 |
59 | # dotenv environment variables file
60 | .env
61 |
62 | # parcel-bundler cache (https://parceljs.org/)
63 | .cache
64 |
65 | # next.js build output
66 | .next
67 |
68 | # nuxt.js build output
69 | .nuxt
70 |
71 | # Nuxt generate
72 | dist
73 |
74 | # vuepress build output
75 | .vuepress/dist
76 |
77 | # Serverless directories
78 | .serverless
79 |
80 | # IDE / Editor
81 | .idea
82 |
83 | # Service worker
84 | sw.*
85 |
86 | # macOS
87 | .DS_Store
88 |
89 | # Vim swap files
90 | *.swp
91 |
--------------------------------------------------------------------------------
/examples/axios-typescript-nuxt/.prettierrc:
--------------------------------------------------------------------------------
1 | {
2 | "semi": false,
3 | "singleQuote": true
4 | }
5 |
--------------------------------------------------------------------------------
/examples/axios-typescript-nuxt/README.md:
--------------------------------------------------------------------------------
1 | # Axios TypeScript Nuxt Example
2 |
3 | > Note: This example is no longer functional now that SSR support is broken as of the Vue 2.7 upgrade
4 |
--------------------------------------------------------------------------------
/examples/axios-typescript-nuxt/nuxt.config.js:
--------------------------------------------------------------------------------
1 | export default {
2 | mode: 'spa',
3 | plugins: [
4 | './plugins/compositionApi.ts'
5 | ],
6 | buildModules: [
7 | '@nuxt/typescript-build'
8 | ]
9 | }
10 |
--------------------------------------------------------------------------------
/examples/axios-typescript-nuxt/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "swrv-axios-typescript-nuxt-example",
3 | "version": "1.0.0",
4 | "description": "My neat Nuxt.js project",
5 | "author": " ",
6 | "private": true,
7 | "scripts": {
8 | "dev": "nuxt",
9 | "build": "nuxt build",
10 | "start": "nuxt start",
11 | "generate": "nuxt generate"
12 | },
13 | "dependencies": {
14 | "axios": "^0.21.1",
15 | "nuxt": "^2.14.7"
16 | },
17 | "devDependencies": {
18 | "@nuxt/typescript-build": "^0.6.0",
19 | "eslint-config-prettier": "^6.10.0",
20 | "eslint-plugin-prettier": "^3.1.2",
21 | "prettier": "^1.19.1"
22 | }
23 | }
24 |
--------------------------------------------------------------------------------
/examples/axios-typescript-nuxt/pages/index.vue:
--------------------------------------------------------------------------------
1 |
2 |
15 |
16 |
17 |
45 |
--------------------------------------------------------------------------------
/examples/ssr-nuxt/README.md:
--------------------------------------------------------------------------------
1 | # SSR-Nuxt Example
2 |
3 | > Note: This example is no longer functional now that SSR support is broken as of the Vue 2.7 upgrade
4 |
5 | Pagination example server side rendering api responses using
6 | [Nuxt](https://nuxtjs.org/) paginating through blog posts.
7 |
8 | ```sh
9 | yarn install
10 | ```
11 |
12 | Run app locally with hot reloading:
13 |
14 | ```sh
15 | yarn dev
16 | ```
17 |
--------------------------------------------------------------------------------
/examples/ssr-nuxt/layouts/default.vue:
--------------------------------------------------------------------------------
1 |
2 |
5 | Try clicking into the different links to show that a slow api call will
6 | show "loading..." at first, but then SWRV will cache the response, so subsequent
7 | fetches will follow the stale-while-revalidate data fetching/cache strategy. For more
8 | information visit
9 | https://github.com/Kong/swrv
13 |