`<pacem-fetch>` talks to your server without a line of script: point it at a `url`, bind its inputs, read its `result`.
Change an input and it fetches again; it's the browser's `fetch()` API, wired into bindings.
```html
<!-- GET, refetched as the query changes -->
<pacem-fetch id="search" url="/api/products" parameters="{{ { q: #query.value } }}"></pacem-fetch>
<!-- POST, only when asked -->
<pacem-fetch id="save" url="/api/orders" method="POST" autofetch="false" parameters="{{ #order.model }}"></pacem-fetch>
```
## Usage
**Ask.** `url` and `method` (default `GET`) say where and how. `parameters` say what:
on a `GET` they become the querystring, on `POST`/`PUT`/`PATCH` the body: JSON by default, form-urlencoded with `type="raw"`.
A templated url takes its segments from the parameters, and nothing is sent while a mandatory one is missing:
```html
<pacem-fetch url="/api/regions/{id}" parameters="{{ { id: #picker.value } }}"></pacem-fetch>
```
**Let it follow.** With `autofetch` on (the default), any change to `url`, `method`, `parameters`, `headers`, `type`, `as`, `mode` or `credentials` fetches again, after a `debounce` of 100ms.
> A newer request aborts the one in flight, so `result` always matches the latest inputs.
> Want the opposite? `throttle="true"` keeps the ongoing request and skips the new ones.
> Build `parameters` as a **new object** in the binding (`{{ { q: #query.value } }}`).
> Edit fields inside an object you already passed and the reference stays the same: nothing refetches.
Set `diff-by-values="true"` to skip refetches when fresh `parameters` or `headers` carry the very same values.
**Or call it.** `autofetch="false"` waits for `fetch()`, typically from a button. It returns a promise of the `Response`.
```html
<pacem-button on-click="#save.fetch()" disabled="{{ #save.fetching }}">save</pacem-button>
```
**Read it.** `fetching` is `true` while a request is in flight; `result` holds the parsed body.
`as` picks the parsing: `object` (JSON, the default), `text`, `blob` or `image` (a data URL, ready for an `<img>`). An empty body sets `result` to `null`.
**React to it.** `success` fires on any 2xx response, `fetchresult` once the body is parsed, `error` on any other status (its `detail` is the `Response`).
> A network failure (offline, CORS, DNS) is no response at all: no `error` event, the `fetch()` promise rejects instead.
## Examples
### Send a message A manual `POST`: the button fires it and stays disabled while it's in flight. Add some delay to watch `fetching`.
### A sortable list A `GET` that follows two selects: every new sort is a fresh `parameters` object, hence a new request.
To provide the best experiences, we use technologies like cookies to store and/or access device information. Consenting to these technologies will allow us to process data such as browsing behavior or unique IDs on this site. Not consenting or withdrawing consent, may adversely affect certain features and functions.