|
| 1 | +# Fetch |
| 2 | + |
| 3 | +> The [Fetch API](https://developer.mozilla.org/en-US/docs/Web/API/Fetch). |
| 4 | +
|
| 5 | +## State |
| 6 | + |
| 7 | +The `useFetch` function exposes the following reactive state: |
| 8 | + |
| 9 | +```js |
| 10 | +import { useFetch } from 'vue-use-web'; |
| 11 | + |
| 12 | +const { isLoading, json, text, error, success } = useFetch('http://myurl.com'); |
| 13 | +``` |
| 14 | + |
| 15 | +| State | Type | Description | |
| 16 | +| --------- | --------- | -------------------------------------------------------------- | |
| 17 | +| isLoading | `Boolean` | If the request is pending. | |
| 18 | +| error | `Boolean` | If the request resulted in a non 200 status code. | |
| 19 | +| success | `Boolean` | If the request is successful. i.e resulted in 200 status code. | |
| 20 | +| json | `any` | The response body as JSON. | |
| 21 | +| text | `string` | The raw response body as a string. | |
| 22 | + |
| 23 | +## Methods |
| 24 | + |
| 25 | +The `useFetch` function exposes the following methods: |
| 26 | + |
| 27 | +```js |
| 28 | +import { useFetch } from 'vue-use-web'; |
| 29 | + |
| 30 | +const { cancel } = useFetch(elem); |
| 31 | +``` |
| 32 | + |
| 33 | +| Signature | Description | |
| 34 | +| --------- | ----------------------------------------------------------------------------------------------------------------------------------- | |
| 35 | +| `cancel` | Cancels the fetch request if browser supports `AbortController`, otherwise the request will complete but will not update the state. | |
| 36 | + |
| 37 | +## Example |
| 38 | + |
| 39 | +```vue |
| 40 | +<template> |
| 41 | + <div> |
| 42 | + <div>{{ isLoading }}</div> |
| 43 | + <div>{{ success }}</div> |
| 44 | + <div>{{ text }}</div> |
| 45 | + <div>{{ blob }}</div> |
| 46 | + <div>{{ json }}</div> |
| 47 | + <div>{{ cancelled }}</div> |
| 48 | + <button @click="cancel">Cancel Request</button> |
| 49 | + </div> |
| 50 | +</template> |
| 51 | +
|
| 52 | +<script> |
| 53 | +import { useFetch } from "vue-use-web"; |
| 54 | +
|
| 55 | +export default { |
| 56 | + setup() { |
| 57 | + const { |
| 58 | + isLoading, |
| 59 | + error, |
| 60 | + success, |
| 61 | + cancel, |
| 62 | + text, |
| 63 | + blob, |
| 64 | + json, |
| 65 | + cancelled |
| 66 | + } = useFetch("/data.json"); |
| 67 | +
|
| 68 | + return { isLoading, error, success, cancel, text, blob, json, cancelled }; |
| 69 | + } |
| 70 | +}; |
| 71 | +</script> |
| 72 | +``` |
| 73 | + |
| 74 | +TODO: useFetch example |
0 commit comments