0.1.2 • Published 11 months ago

@hardwework/use-ful-query v0.1.2

Weekly downloads
-
License
-
Repository
-
Last release
11 months ago

sidebar_position: 2

useQuery

Installation

npm install @hardwework/use-query

generateApiClient

Parameters

ParameterTypeDefaultDescription
baseUrlstringAxios base url
timeoutnumber5000Default timeout (milliseconds)
authorizationHeaderstring"Authorization"Authorization header name
authorizationPrefixstring"Bearer "The authorization header prefix, for example Authorization: Bearer your_token_from_localstorage
localStorageKeystring"token"Local storage key that contains the authentication token

generateJwtApiClient

Parameters

ParameterTypeDefaultDescription
baseUrlstringAxios base url
timeoutnumber5000Default timeout (milliseconds)
authorizationHeaderstring"Authorization"Authorization header name
authorizationPrefixstring"Bearer "The authorization header prefix, for example Authorization: Bearer your_token_from_localstorage
accessTokenLocalStorageKeystring"accessToken"Local storage key that contains the access token
refreshTokenLocalStorageKeystring"refreshToken"Local storage key that contains the refresh token
refreshTokenFunctionfunctionAn asyncronous function that receives the old access token and refresh token and returns newAccessToken, newRefreshToken

useQuery

Parameters

ParameterTypeDefaultDescription
urlstringEndpoint url
methodstring'GET'Request method (GET, POST...)
executeImmediatelybooleanfalseSets whether the call should be executed when the component is created or wait for the call to executeQuery()
onSuccess(response) => void() => { }Function executed after a successful query
onUnauthorized(error) => voidundefinedFunction executed after an unsuccessful query if the response code is 401 (optional, see onError). The default function is the one defined in the ApiProvider if it is not specified in useQuery. To disable the default one and not use an onUnauthorized set onUnauthorized=null
onError(error) => void() => { }Function executed after an unsuccessful query. If onUnauthorized is not defined, it also handles 401 status code
clientOptionsobject{}Extra Axios options, ex. {timeout: 1000}

Returned parameters

ParameterTypeDescription
isLoadingbooleantrue while the query is being executed, false otherwise, even if it has not yet started
isErrorbooleantrue while the query finished unsuccessfully, false otherwise
isSuccessbooleantrue while the query finished successfully, false otherwise
responseanyThe query response if it finished successfully, undefined otherwise
erroranyThe generated error if the query finished unsuccessfully, undefined otherwise. If it got a response, it can be accessed via error.response
executeQuery(data?: {}) => voidTrigger the query with optional body as parameter

useMultipleQueries

Parameters

ParameterTypeDefaultDescription
queriesobjectObject where the key is the name of the query. The content variables are described below.
-- urlstringEndpoint url
-- methodstring'GET'Request method (GET, POST...)
-- dataobject{ }Request body
-- onSuccess(response) => voidFunction executed after a successful query
-- onUnauthorized(error) => voidFunction executed after an unsuccessful query if the response code is 401 (optional, see onError). The default function is the one defined in the ApiProvider if it is not specified in useMultipleQueries. To disable the default one and not use an onUnauthorized set onUnauthorized=null
-- onError(error) => voidFunction executed after an unsuccessful query. If onUnauthorized is not defined, it also handles 401 status code
executeImmediatelybooleanfalseSets whether the call should be executed when the component is created or wait for the call to executeQueries()
onEnd(response) => void() => { }Function executed after after all the queries finished
clientOptionsobject{}Extra Axios options, ex. {timeout: 1000}

Returned parameters

ParameterTypeDescription
executeQueries(data?: {}) => voidStart the queries with optional body as parameter. data should be an object where the key is the name of the query and the value is the actual query data
errorsobjectObject containing all the received errors. The key is the name of the query, the value is the error
responsesobjectObject containing all the received successful responses. The key is the name of the query, the value is the response
statusesobjectObject containing the status of each query. The key is the name of the query, the value is the status
isLoadingbooleantrue if any calls are in progress, false otherwise, even if it has not yet started
queriesobjectContains all the information of each query. The key is the name of the query, the value is an object with the following queries: status, error, response

Examples

Example 1

const { isLoading, executeQuery } = useQuery({
  url: "accounts/login/", // If baseUrl has been set, you can use a relative url. It also accepts absolute urls.
  method: "POST",
  executeImmediately: false,
  onSuccess: (response) => {
    console.log(response);
  },
  onUnauthorized: (response) => {
    console.log(response);
  },
});

const submitForm(value) => {
  executeQuery(value);
}

if(isLoading)
  return <Loader />
else
  return <Form submitForm={submitForm} />

Example 2

const { isLoading, isSuccess, data, error } = useQuery({
  url: "api/v1/userinfo/",
  method: "GET",
  executeImmediately: true,
});

if (isLoading) return <Loader />;
else if (isSuccess) return <UserInfo data={data} />;
else return <Error error={error} />;

Example with useMultipleQueries

const { queries } = useMultipleQueries({
  queries: {
    query1: {
      url: "https://jsonplaceholder.typicode.com/todos/1",
      onSuccess: (response) => {
        console.log("query1", response);
      },
    },
    query2: {
      url: "https://jsonplaceholder.typicode.com/todos/2",
      onError: (error) => {
        console.log("query2 error", error);
      },
      onSuccess: (response) => {
        console.log("query2 success", response);
      },
    },
    query3: {
      url: "https://wrongdomain/todos/3",
      onError: (error) => {
        console.log("query3", error);
      },
    },
  },
  executeImmediately: true,
  onEnd: () => {
    console.log("All done");
  },
});

Example with JWT

import axios from "axios";
import { generateJwtApiClient, ApiProvider } from "@hardwework/use-query";
...
const apiClient = generateJwtApiClient({
  baseUrl: "https://my.api.com/api/v1",
  authorizationHeader: "Authorization",
  authorizationPrefix: "Bearer ",
  refreshTokenFunction: async ({accessToken, refreshToken}) => {
    const response = await axios.post("https://example.com/refresh", {accessToken, refreshToken})
    const updatedAccessToken = response.data.accessToken;
    const updatedRefreshToken = response.data.refreshToken;
    return [updatedAccessToken, updatedRefreshToken];
  }
})
...
root.render(
  <React.StrictMode>
    <ApiProvider apiClient={apiClient} onUnauthorized={(response) => {console.log(response)}}>
      <App />
    </ApiProvider>
  </React.StrictMode >
);
0.1.2

11 months ago

0.1.1

11 months ago

0.1.0

11 months ago