@ltipton/useapi
v0.2.1
Published
React Hooks library for calling APIs
Readme
Build Client API
- Generates hooks to make API calls based on a passed in Api Options
- Allows defining a simple model for a group of endpoints to generate the hooks
Api Options
- The Options are split into two parts
queriesandmutations - With each, a
route-modelshould be defined for each individual endpoint
Query Endpoints
- All query endpoints should be defined under
queriesproperty - All endpoints defined within the
queriesproperty will make agetrequest- The
getrequest is hard coded, and currently can not be changed
- The
Mutation Endpoints
- All mutation endpoints should be defined under
mutationsproperty - Mutation endpoints can make request of the following types
post,patch,put,delete
- Other than the
deletemethods, each mutation hook accepts apayloadobject- The
payloadobject should include the body content of the request
- The
Route model
- Both
queriesandmutationsare defined by aroute-model - A
route-modelis defined by the following propertiesmethod- The HTTP verb to use when making the requestroute- The request url path name, i.e./strategies/23/pillars- Can be a string or function
- As a function, it will be called with the
Hook Optionspassed to the calling hook
payload- Used as the body of the request formutationsonlyonError- Callback called when an error is thrown durning the requestonSuccess- Callback called when a request is successfulonBefore- Callback called before a request is made- Useful for validating the payload of a mutation
- If this callback throws an error, it will be caught
- All caught errors will skip the request and be passed to the
onErrorcallback as aNetworkError - If this callback returns
false, a generic error will be throw - The callback should return anything other than
falseto not throw an error
onUnMount- Callback called when agetrequest is made and the calling Component unmounts- Useful for cleaning up local state when desired
Api Options Example
const endpointHooks = buildApiClient({
queries: {
getAll: {
// Will use 'get' regardless of what is defined here
method: `get`,
route: `/api/endpoint/pathname`,
// Called when the parent component is unmounted
onUnMount: () => {},
// Called when a error is thrown durning a request
// This includes errors in the `onBefore` callback
onError: (error: any) => {},
// Called when a request is successful
onSuccess: <T>(result: T) => {},
},
get: {
method: `get`,
// The route as a function
route: (data: HookMethodOptions) => `/endpoint/${data.payload.id}`,
// Callback methods are not required
},
},
mutations: {
create: {
// Can be any mutation HTTP verb - post, put, patch, delete
method: 'post',
// Accepts all the same arguments as queries
// The `onUnMount` callback is ignored for all mutations
},
},
})Api Client Hooks
- The
buildApiClientmethod returns an object with properties matching the passed inApi Optionsobject - It is split into two parts
queriesandmutationssame as theApi Optionsobject - Within both the
queriesandmutationsproperties are React Hook functions- These are real hooks and follow all the same rules as normal react hooks
- They must be called within the body of a
Function Component - They can NOT be called conditionally
- These hooks use closures
- This allows them to maintain access to the
Api Optionsobject originally passed when they were being built - This allows defining properties and logic for an API request in a single location, and then reusing it where needed
- This allows them to maintain access to the
- It is recommended to export the hooks built from the
buildApiClientmethod using theuseprefix- This is the same pattern used by react, let others know it is a hook, and not regular function
- For example:
- If I have a hook called
getItem - I would export it as
useItem
- If I have a hook called
Hooks Example
- Given the same
endpointHooksas defined in the above example - The
buildApiClientmethod would return the following object
const endpointHooks = {
queries: {
// Contains references to the queries.get route-model above
get: useQuery,
// Contains references to the queries.getAll route-model above
getAll: useQuery,
}
mutations: {
// Contains references to the mutations.create route-model above
create: useMutation,
}
}Query Hooks
- The
useQueryhook is built internally when thebuildApiClientmethod is called - All
route-modeldefined in thequeriesproperty of theApi Optionswill be converted into auseQueryhook - These hooks can be access from the
queriesproperty of the response of thebuildApiClientmethod call- For example:
- Given I pass the following
Api Optionsobject =>{ queries: { get: { ...<route-model> }}} - I can access the hook for the
gethook in the response frombuildApiClientatresponse.queries.get
- Given I pass the following
- For example:
- Unlike the
mutationhooks, the request made by theuseQueryhook are initiated immediately
Query Hook Options
- This hook accepts an
optionsobject with the similar properties as in the initialApi Optionsobjectroute-model - Properties in this object will impact original
route-modelproperties in the following ways- payload => Is merged with the original payload
- onBefore | onSuccess | onError | onUnMount => Will overwrite the original method
- These methods can be defined inline without the need for memoization
- The onUnMount callback exists for mutations only
- route => When route is a function, the
optionsobject will be passed as the first argument
- Aside from the above properties, the
optionsobject has the following- enabled - If
false, the API call will be by-passed - cache - If
true, the response will be cached. Future calls will use the cached response until cleared- Cache exists for queries only
- apiOptions - Object passed on to the axios client
- mapper? -
(item: Record<string, any>[]) => any[] - config? - AxiosRequestConfig from the axios library
- mapper? -
- enabled - If
Query Hook Response
- The hook response contains the following properties
- loading - Is
truewhen the API request is in flight - data - The API client response. Is
undefineduntil a successful API call is made - error - Network Error response. Is undefined until an error is thrown, or the API call fails
- clearCache - Clears the cache for the specific API call
- getCache - Returns the cached response for the specific API call
- loading - Is
Mutation Hooks
- The
useMutationhook is built internally when thebuildApiClientmethod is called - All
route-modeldefined in themutationsproperty of theApi Optionswill be converted into auseMutationhook - These hooks can be access from the
mutationsproperty of the response of thebuildApiClientmethod call- For example:
- Given I pass the following
Api Optionsobject =>{ mutations: { post: { ...<route-model> }}} - I can access the hook for the
posthook in the response frombuildApiClientatresponse.mutations.post
- Given I pass the following
- For example:
- Unlike the
queryhooks, the request made by themutationhook are NOT immediately initiated- Instead they return a
useMutationhook that must be called to initiate the API call
- Instead they return a
Mutation Hook Options
- This hook accepts an
optionsobject with the similar properties as in the initialApi Optionsobjectroute-model - Properties in this object will impact original
route-modelproperties in the following ways- payload => Is merged with the original payload
- onBefore | onSuccess | onError | onUnMount => Will overwrite the original method
- These methods can be defined inline without the need for memoization
- The onUnMount callback exists for mutations only
- route => When route is a function, the
optionsobject will be passed as the first argument
- Aside from the above properties, the
optionsobject has the following- enabled - If
false, the API call will be by-passed - apiOptions - Object passed on to the axios client
- mapper? -
(item: Record<string, any>[]) => any[] - config? - AxiosRequestConfig from the axios library
- mapper? -
- enabled - If
Mutation Hook Response
- The hook response contains the following properties
- loading - Is
truewhen the API request is in flight - data - The API client response. Is
undefineduntil a successful API call is made - error - Network Error response. Is undefined until an error is thrown, or the API call fails
- useMutate - Hook that will make the actual API request
- Mutation hooks are not called immediately in the way that query hooks are
- Instead this
useMutationhook is returned and that must be called to initiate the API call
- loading - Is
