Skip to content

Folders and files

NameName
Last commit message
Last commit date

Latest commit

History

4 Commits

Repository files navigation

axios-react-hook

A lightweight React hook for Axios-based API calls with support for all HTTP methods.

npmlicenseOpen in StackBlitz

v2.0.0 — V2 is now the default import. V2 is built on top of V1 — all V1 behaviour is preserved and the positional-arg API remains available via the published V1 package (npm install axios-react-hook@1). Existing ^1.0.0 users are not affected — npm never auto-upgrades across major versions.


V1 vs V2 at a glance

V1V2
Installnpm install axios-react-hook@1npm install axios-react-hook
Importimport useAxios from 'axios-react-hook'import useAxios from 'axios-react-hook'
ConfigPositional argsObject config
Returnsdata, loading, error, refetchdata, loading, error, status, refetch, cancel
Query paramsparams
Per-request headersheaders
Timeouttimeout
CallbacksonSuccess, onError
CancellationAbortController — auto + manual
Status codestatus

Installation

# V2 (latest)
npm install axios-react-hook
# V1 (pin to old major)
npm install axios-react-hook@1

Quick Start

V2 (default)

importuseAxiosfrom'axios-react-hook';functionPosts(){const{ data, loading, error, status }=useAxios({url: 'https://jsonplaceholder.typicode.com/posts',params: {_limit: 10},});if(loading)return<p>Loading…</p>;if(error)return<p>{status}{error.message}</p>;return(<ul>{data.map(post=><likey={post.id}>{post.title}</li>)}</ul>);}

V1

importuseAxiosfrom'axios-react-hook';// npm install axios-react-hook@1functionPosts(){const{ data, loading, error }=useAxios('https://jsonplaceholder.typicode.com/posts');if(loading)return<p>Loading…</p>;if(error)return<p>Error: {error.message}</p>;return(<ul>{data.map(post=><likey={post.id}>{post.title}</li>)}</ul>);}

Features

V2

  • ✅ Object-based config — readable, no positional-arg juggling
  • ✅ Query params serialised into the URL automatically
  • ✅ Per-request headers and timeout
  • onSuccess / onError callbacks
  • AbortController cancellation — prevents race conditions and unmount warnings
  • ✅ HTTP status code in return value
  • cancel() to abort in-flight requests manually
  • ✅ Auto-fetch on mount, manual trigger via refetch()
  • ✅ Supports GET, POST, PUT, PATCH, DELETE and more
  • ✅ Pass your own Axios instance

V1

  • ✅ Positional-argument API — useAxios(url, method, body, auto, instance)
  • ✅ Auto-fetch on mount and on URL change
  • ✅ Manual trigger via refetch()
  • ✅ Custom Axios instance support

API Reference

V2 Options

OptionTypeDefaultDescription
urlstringRequest URL (required)
methodstring'get'HTTP method: getpostputpatchdelete
bodyanynullRequest body (POST / PUT / PATCH / DELETE)
paramsobjectnullURL query parameters e.g. { page: 1, limit: 10 }
headersobjectnullPer-request headers
timeoutnumber0Request timeout in ms (0 = no timeout)
autobooleantrueAuto-fire on mount and whenever config changes
instanceAxiosInstanceaxiosCustom axios instance
onSuccessFunctionnullCalled with (data, response) on success
onErrorFunctionnullCalled with (error) on failure

V2 Return value

KeyTypeDescription
dataanyResponse payload
loadingbooleantrue while a request is in flight
errorErrorError from the last failed request
statusnumberHTTP status code (200, 404, …) or null
refetchFunctionManually trigger the request
cancelFunctionCancel the currently in-flight request

V1 Parameters

ParameterTypeDefaultDescription
urlstringRequest URL (required)
methodstring'get'HTTP method
bodyanynullRequest body / payload
autobooleantrueAuto-fire on mount and URL change
instanceAxiosInstanceaxiosCustom axios instance

V1 Return value

KeyTypeDescription
dataanyResponse payload
loadingbooleantrue while a request is in flight
errorErrorError from the last failed request
refetchFunctionManually trigger the request

Migrating V1 → V2

// Before (V1)importuseAxiosfrom'axios-react-hook';// @1const{ data, loading, error, refetch }=useAxios(url,method,body,auto,instance);// After (V2)importuseAxiosfrom'axios-react-hook';// @latestconst{ data, loading, error, status, refetch, cancel }=useAxios({
url, method, body, auto, instance,});

Examples

POST request (V2)

importuseAxiosfrom'axios-react-hook';functionCreatePost(){const{ data, loading, error, status, refetch }=useAxios({url: 'https://jsonplaceholder.typicode.com/posts',method: 'post',body: {title: 'Hello',body: 'World',userId: 1},auto: false,onSuccess: data=>console.log('Created:',data),});return(<div><buttononClick={refetch}disabled={loading}>{loading ? 'Creating…' : 'Create Post'}</button>{error&&<p>{status}{error.message}</p>}{data&&<p>Created ID: {data.id}</p>}</div>);}

Custom Axios instance (V2)

importaxiosfrom'axios';importuseAxiosfrom'axios-react-hook';constapi=axios.create({baseURL: 'https://api.example.com',headers: {Authorization: `Bearer ${token}`},});functionProfile(){const{ data, loading, status }=useAxios({url: '/me',instance: api});if(loading)return<p>Loading…</p>;return<p>Hello, {data?.name}</p>;}

Changelog

See CHANGELOG.md.


License

MIT © Muhammed Rashid

About

A lightweight React hook for Axios-based API calls with support for all HTTP methods.

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages