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

use-query-fetch

v2.1.1

Published

This project provides custom React hooks, `useQuery` and `useMutation`, that simplify data fetching and mutation using the Fetch API. The main purpose of building these hooks is to integrate seamlessly with **React Query**, enhancing state management for

Downloads

30

Readme

Custom React Query Hooks

This project provides custom React hooks, useQuery and useMutation, that simplify data fetching and mutation using the Fetch API. The main purpose of building these hooks is to integrate seamlessly with React Query, enhancing state management for server data.

Key Features

  • Caching: Automatically caches GET requests to reduce network load.
  • Refetch on Window Focus: Detects when the browser tab is focused and refetches data, bypassing cached responses.
  • Error Handling: Provides detailed error information when requests fail.
  • Custom Request Configurations: Supports flexible configurations such as different HTTP methods, request bodies, and custom headers.
  • Callback Support: Includes optional callbacks (e.g., onSuccess) that trigger when the data is successfully fetched.

Features

  • useQuery: Fetches data from an API endpoint and handles success and error scenarios with optional callbacks.
  • useMutation: Performs data modifications manages the request's state and responses.
  • Configurable: Allows for flexible configuration, including cache time and refetching on window focus.

Usage

Fetch config & Fetch Client

Fetch Config

  • This fetchConfig object is a configuration object that controls two key behaviors for fetching data: refetching on window focus and caching time.

  • Here's a breakdown of how it's types:

    type FetchConfigType = {
      refetchOnWindowFocus?: boolean; // default false
      cacheTime?: number; // default 1 minute
    };
    • refetchOnWindowFocus: A boolean option that determines whether the data should be refetched when the browser window gains focus again. If set to true, the app will refetch the data every time the user switches back to the browser tab (similar to React Query's refetchOnWindowFocus behavior).

    • cacheTime: A number (in milliseconds) that defines how long the fetched data will be cached before it becomes stale and needs to be refetched. In this case, it's set to 60 * 1000, which is 60 seconds (or 1 minute). You can modify this time to control how long data should remain cached.

Fetch Client

  • The FetchClient class provides a robust framework for handling data fetching and caching in a React application. It simplifies the process of managing cache, and refetching queries, ensuring that your application's data stays fresh and consistent.
    • getQueryCacheData - Takes a key as params and gets the ached data corresponding to the key.
    • refetchQueries - Takes a key as params and refetched any query that matches to key. Very usefull when any data is mutate and requies latest data to be shown!

Basic Usage Example

Consume FetchWrapper

  • Here's how to consume the FetchWrapper :

        import { FetchClient } from "use-query-fetch";
    
        export const client = new FetchClient({
            refetchOnWindowFocus: true,
        });
        const App = () => {
            return  <FetchWrapper client={client.defaultOptions}>
            {...}
          </FetchWrapper>
        };
    • As the client equipped with the Parent methods, later we can use it for other cases with the same configeration so export it can be usefull.

useQuery

  • Here's how to use the useQuery hook to fetch data:
import { useQuery } from "use-query-fetch";

const MyComponent = () => {
  const { data, isLoading, isError, error } = useQuery<
  //expected Response TYPES
   {message:string;reults:number}>({
        queryKey: 'your-key', // `Every key should be unique so that every cached data has their own identifier and can be used later`
        queryFn: asyn()=>{
            // must be an ASYNC funtion
            // Your api call here
        }
    },{
        onSuccess: (data) => console.log("Data loaded successfully:", data), // Fires when success
        // data will get the type defination you pass above.
        onError: (error) => console.error("Error posting data:", error), // Fires when error occurs
    })

  if (isLoading) return <p>Loading...</p>;
  if (isError) return <p>Error occurred.</p>;

  return <div>{JSON.stringify(data)}</div>;
};

useMutation

  • To modify data, you can use the useMutation hook:
import { useMutation } from "use-query-fetch";

const MyComponent = () => {
  const { data, isLoading, isError, error, mutate } = useMutation<
  //expected Payload TYPES
  {title:string}
  >({
        queryFn: asyn()=>{
            // must be an ASYNC funtion
            // Your api call here
        }
    })

  const handleSubmit = () => {
    const payload = {
      /* your data */
    };
    mutate(payload,{
            onError(error) {
              console.error(error); // Fires when error occurs
            },
            onSuccess(data) {
              console.log(data); // Fires when success
            },
          }); // make sure that the payload remains as same expected type
  };

  return (
    <div>
      <button onClick={handleSubmit}>Submit Data</button>
      {isLoading && <p>Loading...</p>}
      {isError && <p>Error occurred: {JSON.stringify(error)}</p>}
    </div>
  );
};

Fetch Client (Contd.)

  • As now Fetch Client has the capacity to get some cached data and refetch api based onto key. Some updates can be done with this and more yet to come

    1. Refetch Queries: If client finds any cached data corresponding to that key. It re-fetches that exact query for the exact key.
    // here the exported client come in handy!
    client.refetchQueries("keys");
    // or
    // also can be called inside some callbacks
    mutate(
      { title: "Hi" },
      {
        onSuccess() {
          client.refetchQueries("keys"); // unique keys & makes sure that the latest data is fetched after mutating. :D
        },
      }
    );
    1. Suppose You want a Sepecific query to cached for a specific time other than all the remain queries & want to reftch it every time when the window is focused
      const {defaultOptions} = new FetchClient({
              cacheTime:60*60*1000,
              refetchOnWindowFocus:true
      });
      useQuery<
        //expected Response TYPES
         {message:string;reults:number}>({
              queryKey: 'your-key',
              queryFn: asyn()=>{
              },
              config: {
                  ...defaultOptions
              }
    
          })

Thank you <3.