https://github.com/joshnuss/svelte-http-store
A Svelte store backed by the fetch API
https://github.com/joshnuss/svelte-http-store
fetch http svelte svelte-store
Last synced: about 1 year ago
JSON representation
A Svelte store backed by the fetch API
- Host: GitHub
- URL: https://github.com/joshnuss/svelte-http-store
- Owner: joshnuss
- Created: 2023-04-02T01:38:56.000Z (about 3 years ago)
- Default Branch: main
- Last Pushed: 2023-04-02T02:49:07.000Z (about 3 years ago)
- Last Synced: 2025-04-11T21:52:41.131Z (about 1 year ago)
- Topics: fetch, http, svelte, svelte-store
- Language: JavaScript
- Homepage:
- Size: 37.1 KB
- Stars: 19
- Watchers: 2
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
Awesome Lists containing this project
README
# svelte-http-store
A [Svelte store](https://svelte.dev/docs#run-time-svelte-store) backed by the [`fetch`](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API) API.
## Installation
```sh
pnpm install -D svelte-http-store
```
## Example
```javascript
// in src/lib/stores/cart.js
import { httpStore } from 'svelte-http-store'
// performs a `GET /cart` request
export const cart = httpStore('/cart')
// store.refresh() will request `GET /cart` again
cart.refresh()
// call store.fetch() to mutate:
cart.fetch('/cart', { method: 'PATCH' })
```
Feel free to wrap the `store.fetch()` with functions that fit your domain:
```javascript
// example: function to add items to the cart
cart.add = ({ product, quantity }) => {
const url = `/cart/${product.id}`
const body = JSON.stringify({ quantity })
cart.fetch(url, { method: 'POST', body })
}
// example: function to clear the cart
cart.clear = () => {
cart.fetch('/cart', { method: 'DELETE' })
}
```
## License
MIT