Alpine JS Fetch
Alpine JS magic methods wrapper for fetch API methods 📨
Install
With a CDN
<script
defer
src="https://unpkg.com/alpinejs-fetch@latest/dist/api.min.js"
></script>
<script defer src="https://unpkg.com/alpinejs@3.x.x/dist/cdn.min.js"></script>
With a Package Manager
yarn add -D alpinejs-fetch
npm install -D alpinejs-fetch
import Alpine from 'alpinejs'
import api from 'alpinejs-fetch'
Alpine.plugin(api)
Alpine.start()
Example
GET
<div x-data="{ productData: {} }">
<button @click="productData = await $get('https://dummyjson.com/products/1')">
Get
</button>
<pre x-text="JSON.stringify(productData, null, 2)"></pre>
</div>
POST
<div x-data="{ productData: {} }">
<button
@click="productData = await $post('https://dummyjson.com/products/add', { title: 'BMW Pencil' })"
>
Create
</button>
<pre x-text="JSON.stringify(productData, null, 2)"></pre>
</div>
PUT/PATCH
<div x-data="{ productData: {} }">
<button
@click="productData = await $put('https://dummyjson.com/products/1', { title: 'iPhone Galaxy +1' })"
>
Update
</button>
<pre x-text="JSON.stringify(productData, null, 2)"></pre>
</div>
DELETE
<div x-data="{ productData: {} }">
<button
@click="productData = await $delete('https://dummyjson.com/products/1')"
>
Delete
</button>
<pre x-text="JSON.stringify(productData, null, 2)"></pre>
</div>
Filtering the Response
A lot of the times you only need a property from the response object, this is
usually data
. You'll see/write stuff like this:
Please note, this depends on the API response and not all APIs will share the
same response format.
const { data } = fetch('https://dummyjson.com/products/1')
With this package you can do that by adding [data]
to the end of the URL.
<div x-data="{ productData: {} }">
<button
@click="productData = await $get('https://dummyjson.com/products/1[data]')"
>
Get
</button>
<button
@click="productData = await $get('https://dummyjson.com/products/1[data, status]')"
>
Get
</button>
<pre x-text="JSON.stringify(productData, null, 2)"></pre>
</div>
This works for all the requests and isn't limited to the data
property.
Anything that is part of the response object can be used to filter the response.
For example, [status]
.
Heads up! Syntax is important, the filter property key must be place in square
brackets [x]
.
Nested Filters
Sometimes you don't want the whole object back, in this example data
returns a
lot of information but we only want title
and price
back. Here's how you can
do that.
<button
@click="productData = await $get('https://dummyjson.com/products/1[data.title, data.price]')"
>
Get
</button>
<pre x-text="JSON.stringify(productData, null, 2)"></pre>
</div>
This will return with the first key, in this case data
omitted.
{
"title": "iPhone 9",
"price": 549
}
Note! You can still pass other filters in when using nested filters, something
like [data.title, status]
will work fine!
Stats