Alpine JS magic methods wrapper for fetch API methods 📨
npm install alpinejs-fetchAlpine JS magic methods wrapper for fetch API methods 📨
``html
defer
src="https://unpkg.com/alpinejs-fetch@latest/dist/api.min.js"
>
`
`shell
yarn add -D alpinejs-fetch
npm install -D alpinejs-fetch
`
`js
import Alpine from 'alpinejs'
import api from 'alpinejs-fetch'
Alpine.plugin(api)
Alpine.start()
`
` html`
` html`
@click="productData = await $post('https://dummyjson.com/products/add', { title: 'BMW Pencil' })"
>
Create
` html`
@click="productData = await $put('https://dummyjson.com/products/1', { title: 'iPhone Galaxy +1' })"
>
Update
` html`
@click="productData = await $delete('https://dummyjson.com/products/1')"
>
Delete
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._
`js`
const { data } = fetch('https://dummyjson.com/products/1')
With this package you can do that by adding [data] to the end of the URL.
` html`
@click="productData = await $get('https://dummyjson.com/products/1[data]')"
>
Get
@click="productData = await $get('https://dummyjson.com/products/1[data, status]')"
>
Get
This works for all the requests and isn't limited to the data property.[status]
Anything that is part of the response object can be used to filter the response.
For example, .
_Heads up! Syntax is important, the filter property key must be place in square
brackets [x]._
Sometimes you don't want the whole object back, in this example data returns atitle
lot of information but we only want and price back. Here's how you can
do that.
`html
@click="productData = await $get('https://dummyjson.com/products/1[data.title, data.price]')"
>
Get
This will return with the first key, in this case
data omitted.`json
{
"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!_


