React hooks to interact with an API from a stateless component using axios.
npm i react-api-hooks -sAn example showing how the useParams and useAPI hooks can be used together to filter results from an API.
The useParams hook keeps a params object in it's state, that can be used when making calls to the API.
Use the updateParams method to immediately update the params object, and trigger a refresh.
Use the debouncedUpdateParams method to delay the params update until wait ms have passed between function calls.
(Using the lodash debounce function).
The isStale property indicates whether the is a debounced params update pending.
const FilterExample = () => {
const { params, updateParams, debouncedUpdateParams, isStale } = useParams(booksInitialParams);
const { data = [], error, isLoading } = useAPI(booksURL, { params });
if (error) {
return <Error error={error} />;
}
return (
<>
<div style={{ display: 'flex' }}>
<SearchInput
style={{ flexGrow: 2, flexBasis: 0 }}
onChange={e =>
debouncedUpdateParams({
q: `intitle:${e.target.value.toLowerCase()}`
})
}
defaultValue="react"
/>
<TypeSelect
style={{ flexGrow: 1, flexBasis: 0 }}
onChange={e =>
updateParams({
filter: e.target.value ? e.target.value : undefined
})
}
/>
</div>
{isLoading ? (
<Loading />
) : (
<GoogleBooksList style={{ opacity: isStale ? 0.3 : 1.0 }} data={data} />
)}
</>
);
};
export default FilterExample;