0.0.2 • Published 9 months ago

@togglecorp/toggle-request v0.0.2

Weekly downloads
-
License
ISC
Repository
github
Last release
9 months ago

Toggle Request

A simple request library using react hooks

Features

  • Typesafe
  • Lightweight

Installation

npm install @togglecorp/toggle-request
// or
yarn install @togglecorp/toggle-request

API

The request library exposes two react hooks to execute a request.

  1. useRequest
  2. useLazyRequest

useRequest

useRequest will immediately execute the request when your component renders and returns the result that can be used to render the UI.

// Example usage

const {
    response,
    pending,
    error,
} = useRequest({
    url: `/projects/${id}/`,
    query: {
        limit: 12,
        offset: 1,
    },
    method: 'GET',
    skip: !id,
    onSuccess: (response) => {
        // NOTE: response from the server
        console.info(`Fetched ${response.total} items from server`);
    }
    onFailure: () => {
        console.error('Could not fetch items');
    }
})

The request options for useRequest are listed below:

optionsdescription
urlThe request url (excluding url query)
queryThe query part of the url as object
bodyThe request body
methodThe request method
otherThe request object accepted by fetch excluding body and method
onSuccessCallback called when a request has completed successfully
onFailureCallback called when a request has failed
skipCan be used to skip calling the request
delayCan be used to delay calling a request (in milliseconds)
shouldRetryCan be used to retry a request. This method should return time after which request should be retried.
shouldPollCan be used to poll a request. This method should return time to poll the request.
mockResponseCan be use to define a mock response
preserveResponseCan be used to persist previous response until new response has arrived

The result for useRequest are listed below:

propertydescription
responseThe response from server after the request completes
pendingThe request status
errorThe error from server after the request errors
retriggerUsed to re-execute the request

useLazyRequest

useLazyRequest will only execute the request once user calls the trigger function. When triggering the request, user can define a context value which can be used to define request options: url, query, body, method and other. If there is no context value, user should trigger the request passing null value.

// Example usage

const {
    response,
    pending,
    error,
    trigger,
} = useRequest({
    method: 'PUT',
    url: (ctx) => `/projects/${ctx.id}/`,
    body: (ctx) => ctx.body,
    onSuccess: (response) => {
        // NOTE: response from the server
        console.info(`Updated item ${response.name}`);
    }
    onFailure: () => {
        console.error('Could not update item');
    }
})

const handleSave = useCallback(
    (id, body) => {
        trigger({
            id,
            body,
        });
    },
    [trigger],
);

The request options for useLazyRequest are listed below:

optionsdescription
urlThe request url (can be a function)
queryThe query part of the url as object (can be a function)
bodyThe request body (can be a function)
methodThe request method (can be a function)
otherThe request object accepted by fetch excluding body and method (can be a function)
onSuccessCallback called when a request has completed successfully
onFailureCallback called when a request has failed
delayCan be used to delay calling a request (in milliseconds)
shouldRetryCan be used to retry a request. This method should return time after which request should be retried.
shouldPollCan be used to poll a request. This method should return time to poll the request.
mockResponseCan be use to define a mock response
preserveResponseCan be used to persist previous response until new response has arrived

The result for useLazyRequest are listed below:

propertydescription
responseThe response from server after the request completes
pendingThe request status
errorThe error from server after the request errors
contextThe context of the last request
triggerUsed to re-execute the request. The function accepts one argument to define the request context

RequestContext

The RequestContext uses React Context API to define configurations available throughout all the child components. The context defines transformer functions to transform request url, request option, response and error.

const requestContextValue = {
    transformUrl: transformProjectUrls,
    transformOptions: transformProjectOptions,
    transformResponse: transformProjectResponse,
    transformError: transformProjectError,
};

return (
    <RequestContext.Provider value={requestContextValue}>
        <ProjectApp />
    </RequestContext.Provider>
)
propertiesdescription
transformUrlFunction to transform every url before request is executed
transformOptionsFunction to transform every request options before request is executed
transformResponseFunction to transform every response after a successful response is received
transformErrorFunction to transform every response after a failure response is received

Partially defining types

import { Error, OptionBase } from './my-project-typings';

// eslint-disable-next-line
const useMyLazyRequest: <R, C = null>(requestOptions: LazyRequestOptions<R, Error, C, OptionBase>) => {
    response: R | undefined;
    pending: boolean;
    error: Error | undefined;
    trigger: (ctx: C) => void;
    context: C | undefined,
} = useMyLazyRequest;

const useMyRequest: <R>(requestOptions: RequestOptions<R, Error, OptionBase>) => {
    response: R | undefined;
    pending: boolean;
    error: Error | undefined;
    retrigger: () => void;
} = useMyRequest;

In the example above:

  • OptionBase defines extra property passed to request hooks, that are available on transformer functions.
  • Error defines the error type received from the server

Detailed API

Unfortunately, there is no detailed api documentation yet. Please refer to the source code.

Development

Running locally

# Install dependencies
yarn install

# Build
yarn build

Linting

# Eslint
yarn lint

# Typescript
yarn typecheck
1.0.0-beta.2

9 months ago

1.0.0-beta.0

10 months ago

1.0.0-beta.1

9 months ago

0.1.0-beta.1

2 years ago

0.1.0-beta.0

2 years ago

0.0.2

2 years ago

0.0.1

3 years ago