use-axios-client
Basics
Getting Started

useLazyAxios

Sometimes you don't want to trigger a request as soon as your component renders.

The useLazyAxios hook can be used to make an axios request imperatively at any time. This is useful for scenarios like triggering requests when a user submits a form or changes filter options.

# Example

import { useLazyAxios } from 'use-axios-client';
export default () => {
const [getData, { data, error, loading }] = useLazyAxios({
url: 'https://example/api',
});
return (
<>
{loading && <div>Loading...</div>}
{error && <div>{error.message}</div>}
{data && <div>{data}</div>}
<button onClick={() => getData()}>Get data</button>
</>
);
};

getData also takes a data argument that you can use in place of passing your data to the hook.

<button onClick={() => getData({ animal: 'goat' })}>Get data</button>

# Request

You can refer to the Request Config section of the axios documentation to see an exhaustive list of all request options.

If needed, these additional options can be passed to the hook to configure your request.

PropertyTypeDescription
axiosInstanceAxiosInstanceAn optional axios instance to be used when making the request.
ssrDataanyData optionally passed in from server-side rendering.

# Response

These response values are returned by the useLazyAxios hook and can be used to handle each state of your request.

It also provides several functions that allow you to interact with the request in an imperative way if needed.

PropertyTypeDescription
getDataFunctionA function that can be called to trigger a request.
dataanyThe data response provided by the server.
errorError | nullAn error message when a response is non-2xx.
loadingbooleanThe loading state of the request.
cancelFunctionA function that can be called to cancel an inflight request.
refetchFunctionA function that can be called to trigger a new request.