Security News
Weekly Downloads Now Available in npm Package Search Results
Socket's package search now displays weekly downloads for npm packages, helping developers quickly assess popularity and make more informed decisions.
use-axios-api-call
Advanced tools
Declarative API Call Hooks
yarn add use-axios-api-call
import {useApiCall, axiosRequest} from 'use-axios-api-call'
function Example() {
const {data: pokemonList, fetching: pokemonListLoading} = useApiCall(() => axiosRequest(
{method: "GET", url: "https://pokeapi.co/api/v2/pokemon?limit=1000"}
), []);
const [pokemonName, setPokemonName] = useState(null);
const {data: pokemon, fetching: pokemonLoading} = useApiCall(() => axiosRequest(
{method: "GET", url: `https://pokeapi.co/api/v2/pokemon/${pokemonName}`}
), [pokemonName]);
//...
}
See /example
folder for more detailed implmementation
https://ikrushyou.github.io/use-axios-api-call/
use-axios-api-call
introduces a more declarative way of making GET API calls through axios.
What that means is you can easily fetch results from API based on your current state and display the results in minimal lines of code.
The library also adds a bunch of additional features as well such as automatic cancellation of requests, debouncing, and memoization (coming soon).
import useApiCall from 'use-axios-api-call'
useApiCall(fetchFn, dependencies[, options]) => ({data, fetching, fetched, cancel, fetch})
fetchFn
: function
| Function that handles the actual API call. useApiCall
expects function to return {request, cancel}
. Wrapper function axiosRequest
is provided for ease of use.dependencies
: array
| Dependency array that determines when to re-fetch the data (similar to useEffect
dependency array).options
: object
| optional
initialValue
: any
| initial value to be returned by data
before anything is fetchedtransform
: function
| optional transformer for data to be returned value => newValue
debounce
: number
| time in ms to delay each call for debouncing (useful if your dependency array is related to user typing input).onCatch
: function
| catch function passed to .catch
onCancel
: function
| function called when request is cancelled (normally would be thrown as an error)onFinally
: function
| function called when request is completed (regardless of outcome).data
: any
| data returned from API call (and transform function).fetching
: bool
| is API call in progress (initial value: false
)fetched
: bool
| has the data been successfully fetched (initial value: false
)cancel
: object
| cancel tokenfetch
: function
| function to manually trigger a fetchA simple wrapper around the axios
function in order to inject a cancel token
export default function axiosRequest({ ...config }) {
let cancel = null
const request = axios({
...config,
cancelToken: new CancelToken((c) => (cancel = c))
})
return { request, cancel }
}
Helper function to easily create urls consisting of a baseUrl
, path
, and params
import { urlBuilder } from 'use-axios-api-call';
urlBuilder({
baseUrl: "https://pokeapi.co/api/v2",
path: `/pokemon`,
params: { limit: 1000 }
})
// https://pokeapi.co/api/v2/pokemon?limit=1000
const pokemonName = "pikachu";
urlBuilder({
baseUrl: "https://pokeapi.co/api/v2",
path: `/pokemon/${pokemonName}`,
})
// https://pokeapi.co/api/v2/pokemon/pikachu
Personally, I like to wrap up all of my api calls into a single hook called useApiClient.js
In here, I'll wrap all of the calls in an axios client that has interceptors for authorization headers, refresh tokens, etc.
Here's a simple example:
// useApiClient.js
import {axiosRequest, urlBuilderWithBase} from 'use-axios-api-call'
const BASE_URL = "https://pokeapi.co/api/v2";
const methods = {
GET: "GET",
PUT: "PUT",
POST: "POST",
DELETE: "DELETE"
};
export default function useApiClient() {
const urlBuilder = urlBuilderWithBase(BASE_URL);
return {
pokemon: {
getAll: () => {
const method = methods.GET;
const url = urlBuilder({
path: `/pokemon`,
params: {
limit: 1000
}
})
return axiosRequest({
method, url
})
},
get: ({name}) => {
const method = methods.GET;
const url = urlBuilder({
path: `/pokemon/${name}`
})
return axiosRequest({
method, url
})
},
}
}
}
The usage of this plus useApiCall
would look like this:
const { data: allPokemon, fetching: fetchingAllPokemon, fetched: fetchedAllPokemon } = useApiCall(() => apiClient.pokemon.getAll(), [])
const { data: pokemon, fetching: fetchingPokemon, fetched: fetchedPokemon } = useApiCall(() =>
pokemonName ? apiClient.pokemon.get({ name: pokemonName }) : null,
[pokemonName]
)
MIT © ikrushyou
FAQs
Declarative API Call Hooks
The npm package use-axios-api-call receives a total of 1 weekly downloads. As such, use-axios-api-call popularity was classified as not popular.
We found that use-axios-api-call demonstrated a not healthy version release cadence and project activity because the last version was released a year ago. It has 1 open source maintainer collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
Socket's package search now displays weekly downloads for npm packages, helping developers quickly assess popularity and make more informed decisions.
Security News
A Stanford study reveals 9.5% of engineers contribute almost nothing, costing tech $90B annually, with remote work fueling the rise of "ghost engineers."
Research
Security News
Socket’s threat research team has detected six malicious npm packages typosquatting popular libraries to insert SSH backdoors.