npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@hardwework/use-ful-query

v0.1.2

Published

Simple way to manage your api calls

Downloads

86

Readme


sidebar_position: 2

useQuery

Installation

npm install @hardwework/use-query

generateApiClient

Parameters

| 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 |

generateJwtApiClient

Parameters

| 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] |

useQuery

Parameters

| 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} |

Returned parameters

| 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 |

useMultipleQueries

Parameters

| 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} |

Returned parameters

| 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 |

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 >
);