1.2.7 • Published 7 months ago

easy-query-hooks v1.2.7

Weekly downloads
-
License
MIT
Repository
github
Last release
7 months ago

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

7 months ago

1.2.6

7 months ago

1.2.5

7 months ago

1.2.4

7 months ago

1.2.3

7 months ago

1.2.2

7 months ago

1.2.1

7 months ago

1.2.0

7 months ago

1.1.23

7 months ago

1.1.22

8 months ago

1.1.21

8 months ago

1.1.18

8 months ago

1.1.17

8 months ago

1.1.16

8 months ago

1.1.15

8 months ago

1.1.14

8 months ago

1.1.12

8 months ago

1.1.11

8 months ago

1.1.10

8 months ago

1.1.9

8 months ago

1.1.8

8 months ago

1.1.7

8 months ago

1.1.6

8 months ago

1.1.5

9 months ago

1.1.4

9 months ago

1.1.3

9 months ago

1.1.2

9 months ago

1.1.1

9 months ago

1.1.0

9 months ago

1.0.12

9 months ago

1.0.11

9 months ago

1.0.10

9 months ago

1.0.9

9 months ago

1.0.8

9 months ago

1.0.6

9 months ago

1.0.5

9 months ago

1.0.4

9 months ago

1.0.3

9 months ago

1.0.2

9 months ago

1.0.1

9 months ago

1.0.0

9 months ago