Get an Binding 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 Binding
that reflects the current state of the API call, identified by the combination
of the endpointKey and the params.
useApiData
will invoke the request during rendering if isSSR
is true.
If not passed, isSSR will be determined automatically.
Parameters
endpointKey
stringparams?
EndpointParamsoptions?
EndpointConfig & Options
Returns
Binding
Binding
Examples
import React from "react";
import { useApiData } from "react-api-data";
const Article = props => {
const article = useApiData("getArticle",
{ id: props.articleId },
{ afterSuccess: () => alert(`Article with id ${props.articleId} received successfully`) },);
return (
<>
{article.request.networkStatus === "success" && (
<div>
<h1>{article.data.title}</h1>
<p>{article.data.body}</p>
</div>
)}
</>
);
};
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();
Register your global and endpoint configurations. Make sure you do this before you mount any components using withApiData.
Parameters
globalConfig
GlobalConfigendpointConfig
EndpointConfig
Returns
Object Redux action
Use your own request function that calls the api and reads the responseBody response. Make sure it implements the RequestHandler interface.
Parameters
requestHandler
RequestHandler
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
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 performRequest Action has been deprecated. It is recommended to use the perform action in the Binding or the Action perform, which is returned by the HOC in the actions 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<Binding> Rejects when endpointKey is unknown. Otherwise resolves with Binding after call has completed. Use request networkStatus to see if call was succeeded or not.
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 invalidateRequest Action has been deprecated. It is recommended to use the invalidateCache action in the Binding or the Action invalidateCache, which is returned by the HOC in the actions prop, and in the afterSuccess and afterFailed events in the endpoint configuration.
Parameters
endpointKey
stringparams?
EndpointParamsinstanceId?
string
Returns
Object Redux action to dispatch
Selector for getting a single entity from normalized data.
Parameters
state
Stateschema
Objectid
string | number
Returns
Object | void
Selector to manually get a Request. 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 getRequest selector has been deprecated. It is recommended to use the request property returned by the Binding, which is returned by the HOC.
Parameters
state
StateendpointKey
stringparams
EndpointParamsinstanceId?
string
Returns
Request | void
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 Binding, which is returned by the HOC.
Parameters
state
StateendpointKey
stringparams
EndpointParamsinstanceId?
string
Returns
any
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: {}
})
,
// if you want to override the configs for a certain endpoint, you can do so:
{
editArticle: {
autoTrigger: false,
afterSucces: ({ dispatch, request, requestBody }) => {
dispatch(
invalidateApiDataRequest('getArticle', {
id: request.params.articleId
})
);
},
}
}
)(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: false
props.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.actions.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 Binding or Binding[] added to each property key of the bindings param and a property actions
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 anBinding[]
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 actions property with type Actions.
Examples
While handling the request on the serverside:
const store = initializeStore();
const app = (
<Provider store={store}>
<App />
</Provider>
);
// prerender to determine what requests are being made
await getDataFromTree(app, store);
// Requests are now all done, render for real.
const content = ReactDOMServer.renderToString(app);
// And... continue normal request handling
res.status(200);
res.send(`<!doctype html>\n${content}`);
res.end();
Above sample is highly simplified, please check our with-next
example for something a bit more concrete.
Parameters
tree
ReactNode Your app tree, containing components that calluseApiData
.store
Store Your store. Should be the same store that you have used to wrap your app tree with, otherwise we can't extract the results.
Returns
A promise, if complete, all requests in the tree have been completed.
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.
Type: String enum
Possible values
"ready"
"loading"
"failed"
"success"
Represents an endpoint call.
Properties
data
any The result data of your request, or undefined if your request has not completed, has failed, or has no response body.loading
boolean Returns a boolean whether the binding is currently loading or not.dataFailed
any Generic type which returns the failed state returned by the API, undefined when the call is not completed or succeeded.request
Requestperform
(params?: EndpointParams, body?: any) => Promise<Binding> 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 Binding after call has completed. Use request networkStatus to see if call was succeeded or not. Both the original Binding 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.purge
() => Promise<void> Clears the request and the retrieved data.getInstance
(instanceId: string) => Binding 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: Binding<Array<User>>
};
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<Binding> 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 invalidatepurgeRequest
(endpointKey
string,params?
EndpointParams,instanceId?
string) => Promise<void> Clears the request and the retrieved data.purgeAll
() => 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.
Information about a request made to an endpoint.
Properties
result?
anynetworkStatus
NetworkStatuslastCall
numberduration
numberresponse?
ResponseerrorBody?
anyendpointKey
stringparams?
EndpointParamsurl
string
Map of parameter names to values.
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: ConfigBeforeProps): {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: ConfigBeforeProps): {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: ConfigAfterProps): 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: ConfigAfterProps): 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.defaultParams?
: Object Provide default params for the params included in the url.enableSuspense?
: boolean Enables React Suspense for the endpoint.parseMethod?
: 'json' | 'blob' | 'text' | 'arrayBuffer' | 'formData' Parse responses automatically as json, text or any of the other options. Defaults to 'json'.
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: ConfigBeforeProps): {response: Response, responseBody: any}beforeFailed?
function ({response: Response, responseBody: any}, beforeProps: ConfigBeforeProps): {response: Response, responseBody: any}afterSuccess?
function (afterProps: ConfigAfterProps): voidafterFailed?
function (afterProps: ConfigAfterProps): voidtimeout?
numberenableSuspense?
: boolean Enables React Suspense globally.parseMethod?
: 'json' | 'blob' | 'text' | 'arrayBuffer' | 'formData' Parse responses automatically as json, text or any of the other options. Defaults to 'json'.
-
endpointKey
string -
request
Request -
requestBody?
any
Properties
endpointKey
stringrequest
RequestrequestBody?
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
Type of the Api-data state
Type: Function
Parameters
url
stringrequestProperties
RequestInit Theinit
parameter for fetch.config?
RequestConfig Extra config options for handling the fetch request
Returns
Promise<HandledResponse>
Properties
parseMethod?
: 'json' | 'blob' | 'text' | 'arrayBuffer' | 'formData' Parse response automatically as json, text or any of the other options.
Properties
response
Responsebody
any
Properties
isSSR
booleanenableSuspense?
: boolean Enables React Suspense for this hook.