API
Table of Contents
Hooks
useApiData()
Get an ApiDataBinding for the given endpoint. It will make sure data gets (re-)loaded if needed. This behavior is
based on the autoTrigger
and cacheDuration
settings in EndpointConfig and will, by default, trigger
the call when the endpoint's method is GET
and the call has not yet been triggered before. This makes it possible to use
this hook for the same call in multiple components, without needing to worry about which components needs to trigger the call
and how to share the data between the components. Just "use" the API data in multiple components and the fetching of data will be handled.
In any case it will return an ApiDataBinding
that reflects the current state of the API call, identified by the combination
of the endpointKey and the params.
Parameters
endpointKey
stringparams?
EndpointParams
Returns
ApiDataBinding
ApiDataBinding
Examples
import React from 'react';import { useApiData } from 'react-api-data';const Article = (props) => {const article = useApiData('getArticle', { id: props.articleId });return (<>{article.request.networkStatus === 'success' &&<div><h1>{article.data.title}</h1><p>{article.data.body}</p></div>}</>);}
useActions()
Parameters
none
Returns
Actions
Actions
Examples
const actions = useActions()// Do a perform on any endpoint configured.actions.perform('postArticle', {id: article.id}, {body: 'The body of my article'})// Invalidate the cache on any endpoint configured.actions.invalidateCache('getArticles');// purge the whole apiData store (invalidate all)actions.purgeAll()
Config
configureApiData()
Register your global and endpoint configurations. Make sure you do this before you mount any components using withApiData.
Parameters
globalConfig
ApiDataGlobalConfig -endpointConfig
ApiDataEndpointConfig
Returns
Object Redux action
useRequestHandler()
Use your own request function that calls the api and reads the responseBody response. Make sure it implements the RequestHandler interface.
Parameters
requestHandler
RequestHandler
Redux Actions
afterRehydrate()
Call this after you've re-hydrated the store when using redux-persist or any other method of persisting and restoring the entire apiData state. This is needed to reset loading statuses.
Returns
Object Redux action to dispatch
performApiRequest()
(Deprecated)
Manually trigger an request to an endpoint. Primarily used for any non-GET requests. For GET requests it is preferred to use withApiData.
Deprecated
The performApiRequest Action has been deprecated. It is recommended to use the perform action in the ApiDataBinding or the ApiDataAction perform, which is returned by the HOC in the apiDataActions prop, and in the afterSuccess and afterFailed events in the endpoint configuration.
Parameters
endpointKey
stringparams?
EndpointParamsbody?
anyinstanceId?
string
Returns
Object Redux action to dispatch. Dispatching this returns: Promise<ApiDataBinding> Rejects when endpointKey is unknown. Otherwise resolves with ApiDataBinding after call has completed. Use request networkStatus to see if call was succeeded or not.
invalidateApiDataRequest()
(Deprecated)
Invalidates the result of a request, settings it's status back to 'ready'. Use for example after a POST, to invalidate a GET list request, which might need to include the newly created entity.
Deprecated
The invalidateApiDataRequest Action has been deprecated. It is recommended to use the invalidateCache action in the ApiDataBinding or the ApiDataAction invalidateCache, which is returned by the HOC in the apiDataActions prop, and in the afterSuccess and afterFailed events in the endpoint configuration.
Parameters
endpointKey
stringparams?
EndpointParamsinstanceId?
string
Returns
Object Redux action to dispatch
Selectors
getEntity()
Selector for getting a single entity from normalized data.
Parameters
apiDataState
ApiDataStateschema
Objectid
string | number
Returns
Object | void
getApiDataRequest()
(Deprecated)
Selector to manually get a ApiDataRequest. This value is automatically bind when using withApiData. This selector can be useful for tracking request status when a request is triggered manually, like a POST after a button click.
Deprecated
The getApiDataRequest selector has been deprecated. It is recommended to use the request property returned by the ApiDataBinding, which is returned by the HOC.
Parameters
apiDataState
ApiDataStateendpointKey
stringparams
EndpointParamsinstanceId?
string
Returns
ApiDataRequest | void
getResultData()
(Deprecated)
Get the de-normalized result data of an endpoint, or undefined if not (yet) available. This value is automatically bound when using withApiData. This selector can be useful for getting response responseBody values when a request is triggered manually, like a POST after a button click.
Deprecated
The getResultData selector has been deprecated. It is recommended to use the request property returned by the ApiDataBinding, which is returned by the HOC.
Parameters
apiDataState
ApiDataStateendpointKey
stringparams
EndpointParamsinstanceId?
string
Returns
any
HOC
withApiData()
Examples
withApiData({article: 'getArticle',users: 'getUser',editArticle: 'editArticle' // an endpoint with autoTrigger false}, (ownProps, state) => ({article: {id: ownProps.articleId,},// sometimes you need to call one endpoint multiple times (simultaneously) with different parameter values:users: state.users.map(user => ({userId: user.id})),editArticle: {}}))(MyComponent);// props.article will be an ApiDataBinding// props.users will be an array of ApiDataBinding// props.editArticle will be an ApiDataBinding// props.apiDataActions will be an Actions object// perform can be used to trigger calls with autoTrigger: falseprops.editArticle.perform({id: props.articleId}, {title: 'New Title',content: 'New article content'});// the apiDataAction property can be used to perform actions on any endpoint in the endpoint config, not only those which are in the current binding.props.apiDataActions.invalidateCache('getArticles');
Binds api data to component props and automatically triggers loading of data if it hasn't been loaded yet. The wrapped
component will get an ApiDataBinding or ApiDataBinding[] added to each property key of the bindings param and a property apiDataActions
of type Action.
Parameters
bindings
{ [propName in TPropNames]: string } maps prop names to endpoint keysgetParams
(ownProps: any, state: any) => { [propName in TPropName]?: EndpointParams | EndpointParams[] } optionally provide the URL parameters. Providing anEndpointParams[]
for a binding results in anApiDataBinding[]
added to the property key.
Returns
Function Function to wrap your component. This higher order component adds a property for each binding, as defined in the bindings param of the HOC, to the wrapped component and an additional apiDataActions property with type Actions.
Types and interfaces
These can be used for documentation purposes, but are also available as TypeScript and Flow types and can be imported straight from the react-api-data package.
NetworkStatus
Type: String enum
Possible values
"ready"
"loading"
"failed"
"success"
ApiDataBinding
Represents an endpoint call.
Properties
data
any The result data of your request, or undefined if your request has not completed or has no response body.request
ApiDataRequestperform
(params?: EndpointParams, body?: any) => Promise<ApiDataBinding> Manually trigger a call to the endpoint. The params parameter is merged with the params parameter of the binding. Returns a promise that resolves with an ApiDataBinding after call has completed. Use request networkStatus to see if call was succeeded or not. Both the original ApiDataBinding and the resolved promise contain the result of the performed request.invalidateCache
() => Promise<void> Manually trigger a cache invalidation of the endpoint with the current parameters.getInstance
(instanceId: string) => ApiDataBinding get an independent instance of this binding. This enables you to make multiple (possibly parallel) calls to the same endpoint while maintaining access to all of them.
Examples
type Props = {users: ApiDataBinding<Array<User>>}
Actions
Perform actions on any configured endpoint. These actions do not need to be dispatched.
Properties
perform
(endpointKey
string,params?
EndpointParams,body?
any,instanceId?
string) => Promise<ApiDataBinding> Manually trigger an request to an endpoint. Primarily used for any non-GET requests. For GET requests it is preferred to use withApiData.invalidateCache
(endpointKey
string,params?
EndpointParams,instanceId?
string) => void Invalidates the result of a request, settings it's status back to 'ready'. Use for example after a POST, to invalidatepurgeAll()
() => void Clears the whole apiData redux store. Might be useful fore logout functions. a GET list request, which might need to include the newly created entity.
ApiDataRequest
Information about a request made to an endpoint.
Properties
result?
anynetworkStatus
NetworkStatuslastCall
numberduration
numberresponse?
ResponseerrorBody?
anyendpointKey
stringparams?
EndpointParamsurl
string
EndpointParams
Map of parameter names to values.
ApiDataEndpointConfig
Specification and configuration of an endpoint.
Properties
url
stringmethod
"GET"
|"POST"
|"PUT"
|"PATCH"
|"DELETE"
cacheDuration?
numberresponseSchema?
Object | Array<Object>transformResponseBody?
function (responseBody: Object): NormalizedDatabeforeSuccess?
function (handledResponse: {response: Response, body: any}, beforeProps: ApiDataConfigBeforeProps): {response: Response, responseBody: any} Callback function that allows you to alter a response before it gets processed and stored. Can also be used to validate a response and turn it into a failed request by setting theok
property of the response to false.beforeFailed?
function (handledResponse: {response: Response, responseBody: any}, beforeProps: ApiDataConfigBeforeProps): {response: Response, responseBody: any} Callback function that allows you to alter a response before it gets processed and stored. Can also be used to turn it into a successful request by setting theok
property of the response to true.afterSuccess
function (afterProps: ApiDataConfigAfterProps): boolean | void Callback for executing side-effects when a call to this endpoint results in a "success" networkStatus. Called directly after the state is updated. If set, afterSuccess in globalConfig gets called after this, unlessfalse
is returned.afterFailed
function (afterProps: ApiDataConfigAfterProps): boolean | void Callback for executing side-effects when a call to this endpoint results in a "failed" networkStatus. Called directly after the state is updated. If set, afterFailed in globalConfig gets called after this, unlessfalse
is returned.setHeaders?
function (defaultHeaders: Object, state: Object): ObjectsetRequestProperties?
function (defaultProperties: Object, state: Object): Objecttimeout?
numberautoTrigger?
boolean Trigger calls automatically if needed. Defaults totrue
for GET requests andfalse
for all other requests.
ApiDataGlobalConfig
Global configuration for all endpoints.
Properties
setHeaders?
function (defaultHeaders: Object, state: Object): ObjectsetRequestProperties
function (defaultProperties: Object, state: Object): ObjectbeforeSuccess?
function ({response: Response, body: any}, beforeProps: ApiDataConfigBeforeProps): {response: Response, responseBody: any}beforeFailed?
function ({response: Response, responseBody: any}, beforeProps: ApiDataConfigBeforeProps): {response: Response, responseBody: any}afterSuccess?
function (afterProps: ApiDataConfigAfterProps): voidafterFailed?
function (afterProps: ApiDataConfigAfterProps): voidtimeout?
number
ApiDataConfigBeforeProps
endpointKey
stringrequest
ApiDataRequestrequestBody?
anyApiDataConfigAfterProps
Properties
endpointKey
stringrequest
ApiDataRequestrequestBody?
anyresultData
anydispatch
Function Redux' dispatch function. Useful for state related side effects.getState
Function Get access to your redux state.actions
Actions Perform actions on any configured endpoint
ApiDataState
Type of the Api-data state
RequestHandler
Type: Function
Parameters
url
stringrequestProperties
RequestInit Theinit
parameter for fetch.
Returns
Promise<HandledResponse>
HandledResponse
Properties
response
Responsebody
any