A complete Axios wrapper that uses RxJS observables instead of promises
MIT License
A complete Axios wrapper that uses RxJS observables instead of promises. Same Axios API, but anything that used to return a Promise<T>
will now return an Observable<T>
instead.
Even though there are a few options out there for Axios wrappers converting its promise-based methods to observables, this library offers a few extra features that make it different:
rxjs-axios
.any
. Instead, they default to unknown
, which not only makes things safer but also forces you to add better types to your code.CancelToken
.get
, post
, put
, etc.), while rxjs-axios provide everything available in the Axios instance, like request(..)
, all form-related methods (e.g., postForm(..)
, toFormData(..)
, formToJSON(..)
, etc.), isAxiosError(..)
, defaults
, interceptors
.This library has axios
and rxjs
as required peer dependencies, so don't forget to add them too.
With NPM:
npm i rxjs-axios axios rxjs
With Yarn:
yarn add rxjs-axios axios rxjs
You can use rxjs-axios
the same way as you would do with Axios. The only difference is that request will result in an Observable<AxiosResponse<T>>
, so you'll have to subscribe to the observable to get the response. If you're using TypeScript, remember to add a type to the method's generic 😉.
Simple example:
import { axios } from "rxjs-axios";
import { map } from "rxjs"
axios.get<User[]>("/api/users")
.pipe(map(({ data }) => data))
.subscribe(users => {
// do anything with users array
});
This becomes particularly cleaner on ReactJS, as you can unsubscribe on the useEffect(..)
clean-up callback:
import { ReactElement, useEffect, useState } from "react";
import { axios } from "rxjs-axios";
import { finalize, map } from "rxjs"
function UsersScreen(): ReactElement {
const [pending, setPending] = useState(false);
const [users, setUsers] = useState<User[]>([]);
useEffect(() => {
setPending(true);
const subscription = axios.get<User[]>("/api/users")
.pipe(
map(({ data }) => data),
finalize(() => setPending(false)),
)
.subscribe(setUsers);
// The request will be canceled if the component is unmounted and the
// subscription was not yet complete
return () => subscription.unsubscribe();
}, []);
return (
<DataTable
pending={pending}
data={users}
// ...rest of DataTable props
/>
)
}
Suggestions are always welcome! Please create an issue describing the request, feature, or bug. We'll try to look into it as soon as possible 🙂
Contributions are very welcome! To do so, please fork this repository and open a Pull Request to the main
branch.