|
1 | 1 | <script lang="ts">
|
2 | 2 | import Preview from '$docs/Preview.svelte';
|
3 |
| - |
4 | 3 | import fetchStore from '$svelte-stores/fetchStore';
|
5 |
| - |
6 |
| - // const { loading, data, error } = fetchStore(/*...*/) |
7 | 4 | </script>
|
8 | 5 |
|
9 | 6 | <h1>Usage</h1>
|
10 | 7 |
|
11 | 8 | ```js
|
12 |
| -import { fetchStore } from '@layerstack/svelte-stores'; |
| 9 | +import { fetchStore, initFetchClient } from '@layerstack/svelte-stores'; |
| 10 | + |
| 11 | +const state = fetchStore(); |
| 12 | + |
| 13 | +// Request new data |
| 14 | +state.fetch(url, options?) |
| 15 | + |
| 16 | +// Re-fetch last request (same url and options) |
| 17 | +state.refresh(); |
| 18 | + |
| 19 | +// Clear data |
| 20 | +state.clear(); |
| 21 | + |
| 22 | +// Request inflight |
| 23 | +$state.loading |
| 24 | + |
| 25 | +// Data (success) |
| 26 | +$state.data |
| 27 | + |
| 28 | +// Error (failure) |
| 29 | +$state.error |
| 30 | + |
| 31 | +// Fetch options |
| 32 | +state.fetch(url, { |
| 33 | + as: 'auto' // 'auto' (default, determined by response `Content-Type`) | 'arrayBuffer' | 'blob' | 'formData' | 'json' | 'text' |
| 34 | +}) |
| 35 | + |
| 36 | +// Disable fetching (control externally) |
| 37 | +state.fetch(url, { |
| 38 | + disabled: isDisabled |
| 39 | +}) |
| 40 | + |
| 41 | +// Force re-fetch even if data exists for current url (ignore cache) |
| 42 | +state.fetch(url, { |
| 43 | + force: true |
| 44 | +}) |
| 45 | + |
| 46 | +// Only fetch once (unless `force: true` is also set) |
| 47 | +state.fetch(url, { |
| 48 | + once: true |
| 49 | +}) |
| 50 | + |
| 51 | +// Transform data before updating `$state.data` |
| 52 | +state.fetch(url, { |
| 53 | + onDataChange: (newData, currentData) => { |
| 54 | + // Useful to concat to existing data, transform data, etc. |
| 55 | + return newData; |
| 56 | + }, |
| 57 | +}) |
| 58 | + |
| 59 | +// Evaluate response |
| 60 | +state.fetch(url, { |
| 61 | + onResponseChange: (response, data) => { |
| 62 | + // Useful to check `response.ok` or `response.status`, |
| 63 | + // refresh another fetch (ex. GET) after mutation (POST, PUT, PATCH, DELETE), etc |
| 64 | + // If value returned, will update `$state.data` |
| 65 | + }, |
| 66 | +}) |
| 67 | + |
| 68 | +// Initialize fetch client with global options (context, typically set in `+layout.svelte`) |
| 69 | +initFetchClient({ |
| 70 | + // Useful to set global headers such as `Authorization` |
| 71 | + options: () => { |
| 72 | + return { |
| 73 | + headers: { |
| 74 | + Authorization: `Bearer ${accessToken}` |
| 75 | + } |
| 76 | + }; |
| 77 | + }, |
| 78 | +}) |
13 | 79 | ```
|
0 commit comments