React useApi()
Axios-based React hooks for async HTTP request data. react-use-api
feeds API data to React components when SSR (Server-Side Rendering), and caches the data to Front-End. react-use-api
makes your code consistent between the two sides and also supports diverse UI states for your application.
TypeScript Support
Thread-safe SSR
Installation
❗Axios is a peer dependency (prerequisite) and it has to be installed
NPM
// NPM$ npm i react-use-api axios// or yarn$ yarn add react-use-api axios
Usage
Setup With ApiProvider
// This is optional from client sideReactDom.render , document.getElementById'root'
React Hooks
Parameters
Types
Code
// request the API data again, omit options.useCache=truerequestconfig?: ReactUseApi.Config, keepState = false
With a custom TypeScript data type
Advanced Usages
Fetching API data forcibly
useApi
calls API once only and retains data and state regardless of each time component rerendering unless the config changes. This act is same as invoking request()
.
Cache mechanism
If your application works with SSR, useApi
will use cached API data instead of calling API when rendering your application on client side for the first time.
On the other hand, options.useCache
allows you to tag the API to be saved in cache and share it with the components using the same API.
// without cache and SSR // with useCache
options.useCache=false
means never using cache data
Decision to use cache data globally
loadApiCache ReactDOM.render , document.getElementById'root'
Manually cache data clearing
Skipping useApi
Pagination or infinite scrolling
Config
The config can be an Axios Request Config or a URL string.
// equals to
Options [Optional]
Name | Type | default | Description |
---|---|---|---|
handleData | Function(data: any, state: ReactUseApi.State) | A callback function to deal with the data of the API's response. IMPORTANT Using any state setter in handleData is dangerous, which will cause the component re-rendering infinitely while SSR rendering. | |
dependencies | Object | The additional needed data using in handleData. NOTE : "dependencies" is supposed to immutable due to React's rendering policy. |
|
shouldRequest | Function | () => false | A callback to decide whether useApi re-fetches the API when only re-rendering . Returning true will trigger useApi to re-fetch. This option is helpful if you want to re-request an API when a route change occurs. |
watch | any[] | [] | An array of values that the effect depends on, this is the same as the second argument of useEffect. |
skip | Boolean | false | Sets true to skip API call. |
useCache | Boolean | -- | Sets true to use cached API data if cache exists (calling API and then saves it if there is no cache). Sets false to call API always. By default, useApi uses the cached data provided from SSR. |
State
First State (before calling API)
The first state has only one property loading
before calling API.
Name | Type | Default | Description |
---|---|---|---|
loading | boolean | false | To indicate whether calling api or not. |
fromCache | boolean | false | To tell whether the data come from SSR API cache. |
Full State (after calling API)
The is the full state data structure after the api has responded.
Name | Type | Default | Description |
---|---|---|---|
loading | boolean | false | To indicate whether calling api or not. |
fromCache | boolean | false | To tell whether the data come from SSR API cache. |
data | any | undefined | The processed data provided from options.handleData . |
response | AxiosResponse | undefined | The Axios' response. |
error | AxiosError | undefined | The Axios' error. |
dependencies | Object | undefined | The additional needed data using in handleData. NOTE : "dependencies" is supposed to immutable due to React's rendering policy. |
prevData | any | undefined | The previous data of the previous state. |
prevState | ReactUseApi.State | undefined | The previous state. |
[custom data] | any | You can add your own custom state data into the state by setting up in options.handleData . For example, state.foo = 'bar' . The data always be preserved whether re-rendering. |
Request Function
A function allows requesting API data again. This function will trigger re-render.
Name | Type | Default | Description |
---|---|---|---|
config | ReactUseApi.Config | The config passed from useApi() | An axios' config object to fetch API data. |
keepState | boolean | false | Set to true to maintain current state data, which facilitates combining previous data with current data, such as table list data. |
revalidate | boolean | false | Set to true to fetch API without using cache data. |
Server Side Rendering (SSR)
The biggest advantage of react-use-api
is to make your code consistent for both client and server sides. Unlike using Next.js or Redux, these require you to fetch API data by yourself before feeding it to the React component. react-use-api
does the chores for you and saves all your API data as cache for client side.
react-use-api
guarantees that the SSR for each HTTP request is thread-safe as long as passing the api context with SSR settings to ApiProvider
.
Please be aware that no lifecycle methods will be invoked when SSR.
SSR and injecting cached api data
// server/render.js (based on Express framework)
The cache data has been inserted into your SSR HTML string as well.
The cache data will be cleaned up after calling loadApiCache() by default
SSR Settings of apiContext (ReactUseApi.CustomSettings)
Each property is optional
Name | Type | Default | Description |
---|---|---|---|
cache | LRU<String, ReactUseApi.CacheData | any> | new LRU() | The cache instance based on lru-cache |
axios | AxiosStatic | AxiosInstance | axios | axios instance (http client) |
maxRequests | number | 100 | The maximum of API requests when SSR |
useCacheData | boolean | true | Set true to inject JS cache data into html when calling injectSSRHtml() |
alwaysUseCache | boolean | false | Set true to use cache data always (equivalent to options.useCache = true ) |
clearLastCacheWhenConfigChanges | boolean | true | This is default behavior that the cached data will be removed once the url config of useApi has been changed. Set false to remain the cached data |
debug | boolean | true | Set true to get debug message from console |
clientCacheVar | string | 'USE_API_CACHE' | The JS variable name of cache data |
renderSSR | Function | () => '' | A callback to render SSR string for injectSSRHtml() |
isSSR | Function | () => typeof window === 'undefined' | A function to determine if the current environment is server |
shouldUseApiCache | Function | (config?: ReactUseApi.Config, cacheKey?: string): boolean | Returns true to enable useApi to get the API data from API cache, which is loaded by loadApiCache . Default is true |
Arguments of injectSSRHtml
injectSSRHtml context: ReactUseApi.CustomContext, renderSSR?:string, postProcess?:string, // a callback for after rendering SSR HTML string: string
SSR - Load cached API data
Please don't forget to invoke loadApiCache()
to load the cached API data come from your server side. useApi will use the cache data instead of calling API when rendering your application for the first time.
// src/index.jsx loadApiCache ReactDOM , rootElement
TypeScript Support
All the associated types are provided by the namespace ReactUseApi as long as importing react-use-api
.
NOTE, this only works if you set up compilerOptions.typeRoots: ["node_modules/@types"] in your tsconfig.json.
Support TypeScript v2.9+ only
License
MIT
Icons made by Eucalyp from www.flaticon.com is licensed by CC 3.0 BY.