# use-axios

> Simple Axios hook for React. Use React Suspense to show loading indicator and Error Boundary to handle request errors.

Latest version **1.0.0** (published 2021-08-31) · ISC license · 0 weekly downloads

## Install

```sh
npm install use-axios
pnpm add use-axios
yarn add use-axios
bun add use-axios
```

## Health

**Score 35/100 (D)** — status: abandoned.

Positive: esm support; no vulnerabilities; high maintenance score.

Warnings: low downloads; no types.

Negative: abandoned.

## Facts

| | |
|---|---|
| Version | 1.0.0 |
| Published | 2021-08-31 |
| First published | 2019-04-03 |
| Weekly downloads | 0 |
| License | ISC |
| TypeScript types | none |
| Module format | ESM + CommonJS |
| Dependencies | 2 |
| Unpacked size | 18.4 KB |
| Known vulnerabilities | 0 |
| Install scripts | no |
| GitHub stars | 25 |
| Author | Arno Saine |
| Maintainers | arnosaine |
| Keywords | react, hooks, axios |

## Links

- npm: https://www.npmjs.com/package/use-axios
- Repository: https://github.com/ArnoSaine/use-axios
- Homepage: https://github.com/ArnoSaine/use-axios#readme
- Issues: https://github.com/ArnoSaine/use-axios/issues
- npm.io page: https://npm.io/package/use-axios

## Dependencies (2)

- [@babel/runtime](https://npm.io/package/@babel/runtime.md) ^7.12.5
- [@postinumero/use-async](https://npm.io/package/@postinumero/use-async.md) ^0.1.2

## Alternatives

- [mobx-react](https://npm.io/package/mobx-react.md) — 2.8M weekly downloads
- [rc-tree](https://npm.io/package/rc-tree.md) — 2.6M weekly downloads
- [@react-oauth/google](https://npm.io/package/@react-oauth/google.md) — 1.3M weekly downloads
- [@wagmi/connectors](https://npm.io/package/@wagmi/connectors.md) — 877.0K weekly downloads
- [vee-validate](https://npm.io/package/vee-validate.md) — 836.4K weekly downloads

## Recent versions

- 1.0.0 (latest) — 2021-08-31
- 0.3.7 — 2021-02-09
- 0.3.6 — 2021-02-09
- 0.3.5 — 2020-04-18
- 0.3.4 — 2019-10-17
- 0.3.3 — 2019-10-10
- 0.3.2 — 2019-10-04
- 0.3.1 — 2019-10-02
- 0.3.0 — 2019-10-02
- 0.2.1 — 2019-07-22
- 0.2.0 — 2019-07-19
- 0.1.3 — 2019-05-13
- 0.1.2 — 2019-04-25
- 0.1.1 — 2019-04-03
- 0.1.0 — 2019-04-03

## README

# use-axios

Simple Axios hook for React. Use React Suspense to show loading indicator and Error Boundary to handle request errors.

[TodoMVC example](https://arnosaine.github.io/use-axios/)

> ℹ This is a React hook for data fetching inside a function component body. Use regular `axios` for requests in `onSubmit`, `onClick` etc.

## Install

```sh
npm install axios use-axios
```

## `useAxios(url[, config])`

#### Params

Same as `axios`.

#### Returns

Success response from axios.

#### Throws

Response error from axios or promise for React Suspense.

## Example

```js
import { Suspense } from 'react';
import useAxios from 'use-axios';

function User({ id }) {
  const { data } = useAxios(`/api/users/${id}`);

  return <div>First name: {data.first_name}</div>;
}

function App() {
  return (
    <Suspense fallback="Loading...">
      <User id="1" />
    </Suspense>
  );
}
```

## Handle errors

Create an error boundary, for example using [react-error-boundary](https://github.com/bvaughn/react-error-boundary).

```js
import { Suspense } from 'react';
import ErrorBoundary from 'react-error-boundary';

function MyFallbackComponent({ error, componentStack }) {
  return (
    <>
      <p>
        <strong>Oops! A request error occurred!</strong>
      </p>
      <pre>
        status: {error.response.status}
        {'\n'}
        statusText: {error.response.statusText}
        {'\n'}
        Stacktrace:
        {componentStack}
      </pre>
    </>
  );
}

function App() {
  return (
    <Suspense fallback="Loading...">
      <ErrorBoundary FallbackComponent={MyFallbackComponent}>
        <User id="23" />
      </ErrorBoundary>
    </Suspense>
  );
}
```

To handle error inside a component, use `useAxiosSafe`:

```js
import { useAxiosSafe } from 'use-axios';

function User({ id }) {
  const [error, { data }] = useAxiosSafe(`/api/users/${id}`);
  if (error) {
    return (
      <>
        <p>
          <strong>Oops! A request error occurred!</strong>
        </p>
        <pre>
          status: {error.response.status}
          {'\n'}
          statusText: {error.response.statusText}
        </pre>
      </>
    );
  }
  return <div>First name: {data.first_name}</div>;
}
```

## Caching and refetching

Successful responses with the same (stable JSON stringified) arguments are cached across the application. Components may rerender and call `useAxios` multiple times, and only one HTTP request is made, as long as there is some component mounted using the same arguments.

### `refetch(url[, config])`

Refetch data and update components. Calling this does nothing, if there are no components currently mounted using `useAxios` and same (stable JSON stringified) arguments.

#### Params

Same as `axios`.

#### Refetch example

Remove user and update list of users:

```js
import { Suspense } from 'react';
import { useAxios, refetch } from 'use-axios';
import { delete as del } from 'axios';

function Users() {
  const { data } = useAxios('/api/users');
  return (
    <ul>
      {data.map((user) => (
        <User key={user.id} {...user} />
      ))}
    </ul>
  );
}

function User({ id, first_name }) {
  return (
    <li>
      {first_name}
      <span
        onClick={async () => {
          // Remove user and update list of users
          await del(`/api/users/${id}`);
          refetch('/api/users');
        }}
      >
        ❌
      </span>
    </li>
  );
}

function App() {
  return (
    <Suspense fallback="Loading...">
      <Users />
    </Suspense>
  );
}
```

## Using a custom axios instance

You can use a custom axios instance by calling `create`.

### `create([axios|config])`

#### Params

An axios instance or an optional config object for `axios.create`.

#### Returns

An object with properties `useAxios`, `useAxiosSafe` and `refetch`.

#### Custom axios instance example

```js
import { create } from 'use-axios';

const { useAxios } = create({
  baseURL: 'https://api.example.com',
});
```

## Not ready for Suspense?

Import from `use-axios/loading-state` to use the `{ isLoading, data, error }` style API. Example:

```js
import { useAxiosSafe } from 'use-axios/loading-state';

function User({ id }) {
  const { isLoading, data, error } = useAxiosSafe(`/api/users/${id}`);

  if (isLoading) {
    return 'Loading...';
  }

  return <div>First name: {data.data.first_name}</div>;
}
```

---
_Source: https://npm.io/package/use-axios · Machine-readable twin of the npm.io package page. Health data is recomputed on every publish._
