Gathering detailed insights and metrics for @hybris-software/use-query
Gathering detailed insights and metrics for @hybris-software/use-query
Gathering detailed insights and metrics for @hybris-software/use-query
Gathering detailed insights and metrics for @hybris-software/use-query
npm install @hybris-software/use-query
Typescript
Module System
Node Version
NPM Version
TypeScript (77.32%)
CSS (10.35%)
JavaScript (10.18%)
HTML (2.14%)
Total Downloads
0
Last Day
0
Last Week
0
Last Month
0
Last Year
0
2 Stars
68 Commits
3 Branches
4 Contributors
Updated on May 28, 2024
Latest Version
2.3.19
Package Id
@hybris-software/use-query@2.3.19
Unpacked Size
38.92 kB
Size
7.10 kB
File Count
11
NPM Version
9.6.7
Node Version
20.3.1
Published on
Jul 19, 2023
Cumulative downloads
Total Downloads
4
4
This hook can be used to perform queries to an endpoint. Allows easy management of operations and query status.
It requires an Axios client. This library already provides the generateApiClient
function which returns a client with a variable base url and an interceptor to send an authentication header. You may also create an axios client by your own.
Install the library with npm install @hybris-software/use-query
.
At the upper level of the application you should also insert the ApiProvider
component which requires an apiClient
prop. It should be an Axios client which you can create by your own or use generateApiClient
to generate one.
Here is an example:
1import { generateApiClient, ApiProvider } from "@hybris-software/use-query"; 2... 3const apiClient = generateApiClient({ 4 baseUrl: "https://my.api.com/api/v1", 5 authorizationHeader: "Authorization", 6 authorizationPrefix: "Bearer " 7}) 8... 9root.render( 10 <React.StrictMode> 11 <ApiProvider apiClient={apiClient}> 12 <App /> 13 </ApiProvider> 14 </React.StrictMode > 15);
This function returns an Axios client with the possibility to set a baseUrl
, and an authorization header. It gets the authorization token from localStorage
or sessionStorage
with the key token
.
Parameter | Type | Default | Description |
---|---|---|---|
baseUrl | string | Axios base url | |
timeout | number | 5000 | Default timeout (milliseconds) |
authorizationHeader | string | "Authorization" | Authorization header name |
authorizationPrefix | string | "Bearer " | The authorization header prefix, for example Authorization: Bearer your_token_from_localstorage |
localStorageKey | string | "token" | Local storage key that contains the authentication token |
This is what generateApiClient
generates, you can use it as a base to create your own api client.
1const apiClient = axios.create({ 2 baseURL: baseUrl, 3 timeout: 5000, 4 headers: { 5 "Content-Type": "application/json", 6 Accept: "application/json", 7 }, 8}); 9 10apiClient.interceptors.request.use( 11 function (config) { 12 config.headers = config.headers || {}; 13 const token = 14 localStorage.getItem("token") || sessionStorage.getItem("token"); 15 if (token) { 16 config.headers[authorizationHeader] = `${authorizationPrefix}${token}`; 17 } 18 config.headers["Content-Type"] = "application/json"; 19 config.headers["Accept"] = "application/json"; 20 return config; 21 }, 22 function (error) { 23 return Promise.reject(error); 24 } 25); 26 27apiClient.interceptors.response.use( 28 function (response) { 29 return response; 30 }, 31 function (error) { 32 return Promise.reject(error); 33 } 34);
This function returns an Axios client with the possibility to set a baseUrl
, and an authorization header. It gets the authorization token from localStorage
or sessionStorage
with the key token
.
Parameter | Type | Default | Description |
---|---|---|---|
baseUrl | string | Axios base url | |
timeout | number | 5000 | Default timeout (milliseconds) |
authorizationHeader | string | "Authorization" | Authorization header name |
authorizationPrefix | string | "Bearer " | The authorization header prefix, for example Authorization: Bearer your_token_from_localstorage |
accessTokenLocalStorageKey | string | "accessToken" | Local storage key that contains the access token |
refreshTokenLocalStorageKey | string | "refreshToken" | Local storage key that contains the refresh token |
refreshTokenFunction | function | An asyncronous function that receives the old access token and refresh token and returns [newAccessToken, newRefreshToken] |
This hook performs only one query, if you have to perform multiple queries in parallel you can call multiple times useQuery
or use useMultipleQueries
as described below.
Parameter | Type | Default | Description |
---|---|---|---|
url | string | Endpoint url | |
method | string | 'GET' | Request method (GET, POST...) |
executeImmediately | boolean | false | Sets 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) => void | undefined | Function 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 |
clientOptions | object | {} | Extra Axios options, ex. {timeout: 1000} |
Parameter | Type | Description |
---|---|---|
isLoading | boolean | true while the query is being executed, false otherwise, even if it has not yet started |
isError | boolean | true while the query finished unsuccessfully, false otherwise |
isSuccess | boolean | true while the query finished successfully, false otherwise |
response | any | The query response if it finished successfully, undefined otherwise |
error | any | The generated error if the query finished unsuccessfully, undefined otherwise. If it got a response, it can be accessed via error.response |
executeQuery | (data?: {}) => void | Trigger the query with optional body as parameter |
This hooks allows to perform multiple queries in parallel with a syntax similar to that of useQuery
.
Parameter | Type | Default | Description |
---|---|---|---|
queries | object | Object where the key is the name of the query. The content variables are described below. | |
-- url | string | Endpoint url | |
-- method | string | 'GET' | Request method (GET, POST...) |
-- data | object | { } | Request body |
-- onSuccess | (response) => void | Function executed after a successful query | |
-- onUnauthorized | (error) => void | Function 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) => void | Function executed after an unsuccessful query. If onUnauthorized is not defined, it also handles 401 status code | |
executeImmediately | boolean | false | Sets 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 |
clientOptions | object | {} | Extra Axios options, ex. {timeout: 1000} |
Parameter | Type | Description |
---|---|---|
executeQueries | (data?: {}) => void | Start 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 |
errors | object | Object containing all the received errors. The key is the name of the query, the value is the error |
responses | object | Object containing all the received successful responses. The key is the name of the query, the value is the response |
statuses | object | Object containing the status of each query. The key is the name of the query, the value is the status |
isLoading | boolean | true if any calls are in progress, false otherwise, even if it has not yet started |
queries | object | Contains 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 |
1const { isLoading, executeQuery } = useQuery({ 2 url: "accounts/login/", // If baseUrl has been set, you can use a relative url. It also accepts absolute urls. 3 method: "POST", 4 executeImmediately: false, 5 onSuccess: (response) => { 6 console.log(response); 7 }, 8 onUnauthorized: (response) => { 9 console.log(response); 10 }, 11}); 12 13const submitForm(value) => { 14 executeQuery(value); 15} 16 17if(isLoading) 18 return <Loader /> 19else 20 return <Form submitForm={submitForm} />
1const { isLoading, isSuccess, data, error } = useQuery({ 2 url: "api/v1/userinfo/", 3 method: "GET", 4 executeImmediately: true, 5}); 6 7if (isLoading) return <Loader />; 8else if (isSuccess) return <UserInfo data={data} />; 9else return <Error error={error} />;
1const { queries } = useMultipleQueries({ 2 queries: { 3 query1: { 4 url: "https://jsonplaceholder.typicode.com/todos/1", 5 onSuccess: (response) => { 6 console.log("query1", response); 7 }, 8 }, 9 query2: { 10 url: "https://jsonplaceholder.typicode.com/todos/2", 11 onError: (error) => { 12 console.log("query2 error", error); 13 }, 14 onSuccess: (response) => { 15 console.log("query2 success", response); 16 }, 17 }, 18 query3: { 19 url: "https://wrongdomain/todos/3", 20 onError: (error) => { 21 console.log("query3", error); 22 }, 23 }, 24 }, 25 executeImmediately: true, 26 onEnd: () => { 27 console.log("All done"); 28 }, 29});
1import axios from "axios"; 2import { generateJwtApiClient, ApiProvider } from "@hybris-software/use-query"; 3... 4const apiClient = generateJwtApiClient({ 5 baseUrl: "https://my.api.com/api/v1", 6 authorizationHeader: "Authorization", 7 authorizationPrefix: "Bearer ", 8 refreshTokenFunction: async ({accessToken, refreshToken}) => { 9 const response = await axios.post("https://example.com/refresh", {accessToken, refreshToken}) 10 const updatedAccessToken = response.data.accessToken; 11 const updatedRefreshToken = response.data.refreshToken; 12 return [updatedAccessToken, updatedRefreshToken]; 13 } 14}) 15... 16root.render( 17 <React.StrictMode> 18 <ApiProvider apiClient={apiClient} onUnauthorized={(response) => {console.log(response)}}> 19 <App /> 20 </ApiProvider> 21 </React.StrictMode > 22);
No vulnerabilities found.
No security vulnerabilities found.
Last Day
0%
NaN
Compared to previous day
Last Week
0%
NaN
Compared to previous week
Last Month
0%
NaN
Compared to previous month
Last Year
0%
NaN
Compared to previous year