1.3.2 • Published 2 years ago

@anb98/react-hooks v1.3.2

Weekly downloads
-
License
ISC
Repository
github
Last release
2 years ago

Hooks

Table of Contents

Installation

npm i @anb98/react-hooks

setGlobals

This function allows you to set globals options for useFetch, useFetchData, useLazyFetch and useLazyFetchCache

Usage

import { setGlobals } from '@anb98/react-hooks';

setGlobals({
    baseURL: 'http://your-base-url',
    headers: {},
    withCredentials: true,
})

*You don't need to set / at the end of baseURL

setGlobals options

PropertyDescriptionTypeDefault
baseURLIt sets base url to be concatenate with url of useDataApi optionsstring''
headersRequest headersanynull
withCredentialsEnable cookie credentialsbooleanfalse

useLazyFetch

This hook is a wrapper for usePromise hook which consumes an API when calling the handler function.

Usage

import { useLazyFetch } from '@anb98/react-hooks';

const options = {
    url: 'http://your-endpoint-url',
    initialData: {},
    request: { headers: { example: 'test'} },
    onCancel: () => {},
    onComplete: (data, err) => {},
    onFail: (err) => {},
    onSuccess: (data) => {},
};

const TestComponent = () => {
    const [{ 
        data,
        error,
        isError,
        isLoading,
        isSuccess,
        status,
    }, fetchData, resetState, cancelFetch ] = useLazyFetch(options);
    
    const getData = () => {
        const fetchDataOptions = {
            body:{},
            headers: {},
            method: 'post',
            params: {},
            url: '',
            withCredentials: true
        }

        fetchData(fetchDataOptions);
    };

    return (<button onClick={getData}>test</button>);
};

export default TestComponent;

Initial options

PropertyDescriptionTypeDefault
urlInitial URL to requeststringglobals.baseURL
initialDataInitial data to return as resultanynull
requestRequest config object axiosRequest config axios{}
onFailCallback called when request failsfunction(err)()=>{}
onSuccessCallback called when request failsfunction(data)()=>{}
onCompleteCallback called when request completesfunction(data, err)()=>{}
onCancelCallback called when request cancelsfunction()()=>{}

Returned state

PropertyDescriptionTypeDefault
dataResult of the requestanyinitialData
errorError of the requestanynull
isErrorIt shows if the request failsbooleanfalse
isLoadingIt shows if the request is loadingbooleanfalse
isSuccessIt shows if the request completed successfullybooleanfalse
statusIt shows the request's statusidle | pending | resolved | rejectedidle

resetState function will reset returned state to initial state.

fetchDataOptions options uses type Request config from axios

useFetch

This hook consumes API when component is mounted and also when calling the handler function.

By default it request with GET method unless you change initial options.

This hook is a wrapper for useLazyFetch.

Usage

import { useFetch } from '@anb98/react-hooks';

const options = {
    deps: [],
    initialData: {},
    request: { headers: { example: 'test'} },
    onCancel: () => {},
    onComplete: (data, err) => {},
    onFail: (err) => {},
    onSuccess: (data) => {},
};

const TestComponent = () => {
    const [{ 
        data,
        error,
        isError,
        isLoading,
        isSuccess,
        status,
    }, fetchData, resetState, cancelFetch ] = useFetch('http://your-endpoint-url', options);
    
    const getData = () => {
        const fetchDataOptions = {
            body:{},
            headers: {},
            method: 'post',
            params: {},
            url: '',
            withCredentials: true
        }

        fetchData(fetchDataOptions);
    };

    return (<button onClick={getData}>test</button>);
};

export default TestComponent;

URL first param is mandatory

Initial options

PropertyDescriptionTypeDefault
depsDependency list to run hookArray<any>[]

usePromise

This hook executes a Promise when calling the handler function.

Usage

import { usePromise } from '@anb98/react-hooks';

const promise = (example, test) => Promise.resolve({ example, test });

const options = {
    deps:[],
    params: ['example', 'test'],
    initialData: {},
    onComplete: (data, err) => {},
    onFail: (err) => {},
    onSuccess: (data) => {},
    onUnmount: ()=>{},
};

const TestComponent = () => {
    const [{ 
        data,
        error,
        isError,
        isLoading,
        isSuccess,
        status,
    }, promiseHandler, resetState ] = usePromise(promise, options);
    
    const getPromiseResult = () => {
        promiseHandler('example', 'test');
    };

    return (<button onClick={getPromiseResult}>test</button>);
};

export default TestComponent;

promise function param is mandatory

handlerOptions are passed to promise function; otherwise it passes params from initial options

resetState function will reset returned state to initial state.

Initial options

PropertyDescriptionTypeDefault
depsDependency list to run hookArray<any>[]
paramsDefault params to use in promise handlerany[][]
initialDataInitial data to return as resultanynull
onFailCallback called when promise failsfunction(err)()=>{}
onSuccessCallback called when promise successfunction(data)()=>{}
onCompleteCallback called when promise completesfunction(data, err)()=>{}
onUnmountCallback called when hook is unmountedfunction()()=>{}

Returned state

PropertyDescriptionTypeDefault
dataResult of the requestanyinitialData
errorError of the requestanynull
isErrorIt shows if the request failsbooleanfalse
isLoadingIt shows if the request is loadingbooleanfalse
isSuccessIt shows if the request completed successfullybooleanfalse
statusIt shows the request's statusidle | pending | resolved | rejectedidle

useFetchCache and useLazyFetchCache

This hooks allow to cache results from request previously fetched. To use this hooks you first need CacheProvider.

import { CacheProvider } from '@anb98/react-hooks';

const App = () => (
    <div className="App">
        <CacheProvider>
            <Main/>
        </CacheProvider>
    </div>
);

All the options and returned values for useFetchCache and useLazyFetchCache are the same from useFetch and useLazyFetch respectively.

To refresh the next request you can add { refresh: true } as second param when calling handler.

Example:

<button onClick={()=>handler({}, { refresh: true })}>
    Fetch Cache
</button>

useSearch

This hook filters results when searching.

Usage

import { useSearch } from '@anb98/react-hooks';

const options = {
    allowFields: [],
    denyFields: []
    sourceData: []
};

const TestComponent = () => {
    const {
        setSourceData,
        setSearchValue,
        filtered,
        sourceData
    } = useSearch(options);

    return (
        <div>
            <input type="text" onChange={(evt)=> setSearchValue(evt.target.value) } />

            <ul>
                {
                    filtered.map((el)=>(
                        <li key={el.id}>{JSON.stringify(el)}</li>
                    ))
                }
            </ul>
        </div>
    );
}

Initial options

PropertyDescriptionTypeDefault
allowFieldsFields in which searchArray<string>[]
denyFieldsFields in which not searchArray<string>[]
sourceDataSource data to searchArray<Object>[]

Returned

PropertyDescriptionTypeDefault
setSourceDataFunction to set sourceDatafunction(Array<Object>)
setSearchValueFunction to set search valuefunction(string)
filteredFiltered results from sourceDataArray<string>[]
sourceDataPreviously set source dataArray<Object>[]
1.3.2

2 years ago

1.3.1

2 years ago

1.3.0

2 years ago

1.2.0

2 years ago

1.1.0

3 years ago

1.0.0

3 years ago