import {
Story,
Meta,
html,
} from '@open-wc/demoing-storybook';
import { ajax } from '../src/ajax.js';
import { AjaxClass } from '../src/AjaxClass.js';
# Ajax
`lion-ajax` is the global manager for handling all ajax requests.
It is a promise based system for fetching data, based on
axios
{html`
`}
```js
ajax.get('./packages/ajax/stories/data.json').then(response => console.log(response.data));
```
## Features
- only JS functions, no (unnecessarily expensive) web components
- supports GET, POST, PUT, DELETE, REQUEST, PATCH and HEAD methods
- can be used with or without XSRF token
## How to use
### Installation
```sh
npm i --save @lion/ajax
```
```js
import { ajax, AjaxClass } from '@lion/ajax';
```
## Cancelable Request
It is possible to make an Ajax request cancelable, and then call `cancel()` to make the request provide a custom error once fired.
{html`
`}
```js
const myAjax = AjaxClass.getNewInstance({ cancelable: true });
requestAnimationFrame(() => {
myAjax.cancel('too slow');
});
myAjax
.get('./packages/ajax/stories/data.json')
.then(response => {
console.log(response.data);
})
.catch(error => {
console.log(error);
});
```
## Cancel concurrent requests
You can cancel concurrent requests with the `cancelPreviousOnNewRequest` option.
{html`
`}
```js
const myAjax = AjaxClass.getNewInstance({ cancelPreviousOnNewRequest: true });
myAjax
.get('./packages/ajax/stories/data.json')
.then(response => {
console.log(response.data);
})
.catch(error => {
console.log(error.message);
});
myAjax
.get('./packages/ajax/stories/data.json')
.then(response => {
console.log(response.data);
})
.catch(error => {
console.log(error.message);
});
```
## Considerations
Due to a bug in axios options may leak in to other instances.
So please avoid setting global options in axios. Interceptors have no issues.
## Future plans
- Eventually we want to remove axios and replace it with
Fetch
- This wrapper exist to prevent this switch from causing breaking changes for our users