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

easy-query-hooks

v1.2.7

Published

Utility hooks for React Query

Downloads

48

Readme

easy-query-hooks

Utility hooks for React Query, providing an easy and consistent way to make API calls. Simplifies your React application by abstracting common HTTP methods.

npm version NPM

Table of Contents

  1. Installation
  2. Usage
  3. API
  4. Examples
  5. Contribution
  6. License

Installation

You can install easy-query-hooks using npm or yarn:

npm install easy-query-hooks
# or
yarn add easy-query-hooks

If you havent already you will need to follow the setup for @tanstack

npm install @tanstack/react-query
# or
yarn add @tanstack/react-query

Usage

import { useGetAPI } from "easy-query-hooks";

const TestComponent = () => {
  type post = { title: string };
  const { data: posts, isLoading } = useGetAPI<post[]>({
    url: "https://jsonplaceholder.typicode.com/posts",
  });

  return (
    <>
      {isLoading ? (
        <div>loading</div>
      ) : (
        posts?.map((post) => <div key={post.id} >{post.title}</div>)
      )}
    </>
  );
};

export default TestComponent;

Setup

Like with @tanstack You need to Wrap a provider around the app and pass QueryClient in

setUpEasyQueryHooks({ useMutation, useQuery, useInfiniteQuery } is Required

import {
  QueryClient,
  QueryClientProvider,
  useInfiniteQuery,
  useMutation,
  useQuery,
} from "@tanstack/react-query";
import { setUpEasyQueryHooks } from "easy-query-hooks";

const queryClient = new QueryClient();

setUpEasyQueryHooks({ useMutation, useQuery, useInfiniteQuery });

function App() {
  return (
    <QueryClientProvider client={queryClient}>
      <div className="App">
        <h1>Testing easy-query-hooks</h1>
      </div>
    </QueryClientProvider>
  );
}

export default App;

Before using hooks, you may want to set up default options for (queryOptions,mutationOptions,infiniteQueryOptions), defaultHeaders and customise HTTP client, useful for adding axios.

const customGet = async ({ url, data, header }: HttpClientParams) =>
  axios
    .get(url, {
      headers: header,
    })
    .then((res) => res.data);

setUpEasyQueryHooks({
  useInfiniteQuery,
  useMutation,
  useQuery,
  get: customGet,
  queryOptions: {
    onError: (err: unknown) => {
      if (err instanceof Error) {
        setToast(err.message, "Error");
      }
    },
  },
  defaultHeaders: authHeaders,
  prefixUrl: "https://jsonplaceholder.typicode.com/", 
});

Hooks

useGetAPI

  const { data: posts } = useGetAPI<post[]>({
    url: "https://jsonplaceholder.typicode.com/posts",
  });

usePostAPI

const { mutate } = usePostAPI<TRequest, TResponse>({
  url: '/api/users',
});

usePatchAPI

const { mutate } = usePatchAPI<TRequest, TResponse>({
  url: '/api/users',
});

usePutAPI

const { mutate } = usePutAPI({
  url: '/api/users',
});

useDeleteAPI

const { mutate } = useDeleteAPI({
  url: '/api/users',
});

API

Examples

Using useGetAPI to fetch users

const { data, isLoading, error } = useGetAPI({
  url: '/api/users',
});

if (isLoading) return "Loading...";
if (error) return "An error has occurred: " + error.message;

return (
  <ul>
    {data.map(user => (
      <li key={user.id}>{user.name}</li>
    ))}
  </ul>
);

Using usePostAPI to Post Data

  const { mutate: submitPost } = usePostAPI({
    url: "https://jsonplaceholder.typicode.com/posts",
  });

  const handleSubmit = () => {
    submitPost({
      title: "foo",
      body: "bar",
      userId: 1,
    });
  };

Using useDeleteAPI to Post Data

  const { mutateAsync: deletePost } = useDeleteAPI({
    url: "https://jsonplaceholder.typicode.com/posts/${id}",
  });

  const handleDelete = async() => {
    await deletePost();
  };

Using useGetInfiniteAPI to fetch articles

const { data, fetchNextPage, hasNextPage } = useGetInfiniteAPI({
  url: '/api/articles?sort=desc',
  hasParams: true,
  options: {
    getNextPageParam: (lastPage, pages) => {
      return lastPage.nextPageToken;
    },
  },
});

const fetchMoreArticles = () => {
  if (hasNextPage) {
    fetchNextPage();
  }
};

Contribution

Feel free to open issues or PRs! Check the Contribution Guide for more details.

License

MIT

GitHub Repository: Samuel-Morgan-Tyghe/EasyQueryHooks

Roadmap

This project is under active development, and we're always open to suggestions and contributions. Below is the list of features we're planning to implement in the near future:

Planned Features

1. Advanced Testing Support

  • Status: Not Started
  • Details: Integrate @testing-library/react-hooks to ensure that hooks are functioning as expected.

2. Optional Key Override

  • Status: Not Started
  • Details: Provide an optional mechanism for overriding the query key, allowing for more granular control over queries.

3. Pass ID as Endpoint Parameter

  • Status: Not Started
  • Details: Allow passing IDs directly into the endpoint URL as a parameter (e.g., /posts/{id}/) to simplify state management and improve API design consistency.