withData
Params:
options: HocOptionsurl: stringname: stringqueryParams: Record<string, any>fetchOptions: RequestInit = {}dataOptions: DataHookOptions
To learn more about what
dataOptionscan be passed, go here.
Example usage:
const MyComponent = () => {const { data, loading, error, refetch } = this.props.pokemonData;return (loading? 'loading...': <div>The data is: {JSON.stringify(data)}</div>);};export default withData({// the url string of the endpoint we will send request tourl: 'https://pokeapi.co/api/v2/pokemon/4/',// the name of the prop the data will be injected toname: 'pokemonData',// Object of query paramsqueryParams: {},// Any options that you normally pass to `fetch()`fetchOptions: {method: 'GET',},// dataOptions object. Used to configure some behaviors.dataOptions: {ssr: true,},})(MyComponent);
The response from the REST endpoint will be parsed as JSON, and will throw an error if it is not a valid JSON. The response will be available in the data variable.
The HOC will inject an object as a props named name (depending on the name you passed to the HOC). The object contains the following keys:
data <any>The JSON response from the endpoint
loading <boolean>A
booleanvalue that determine whether a request is currently in-flighterror <Error | null>The
Errorobject, if any error happened during the network request.nullif no error happened.refetch: () => Promise<any>A function that will trigger refetching data from network. Fetching data from network this way will always bypass the cache, no matter what the
fetchPolicyis set to.
Which are basically exactly the same as what useData() is returning.
Supported methods
Same as useData(), only GET requests are supported. Supporting other methods is not in the plan because it can be dangerous to re-request a non-idempotent request on component state update.