tanstack-builder
v1.0.3
Published
This package is designed to simplify the usage of the @tanstack/react-query library by providing utilities to handle common patterns and improve code readability.
Downloads
3
Readme
React Query Wrapper Package
This package is designed to simplify the usage of the @tanstack/react-query library by providing utilities to handle common patterns and improve code readability.
Features
- Automatic aliasing of properties returned from useQuery and useMutation.
- Simplified query and mutation creation with prefixed keys.
- Easy handling of query invalidation after mutations.
Installation
npm install tanstack-builder
Usage/Examples
- Creating Queries
import { useQueryBuilder } from 'tanstack-builder';
export const useGetAllPosts = () => useQueryBuilder({
prefix: "getAllPosts",
defaultOptions: {
queryKey: ['GET_ALL_POSTS'],
queryFn: () => getPosts()
},
})();
export const useGetPostById = (id: number) => useQueryBuilder({
prefix: "getPostById",
defaultOptions: {
queryKey: ['GET_POST_BY_ID', id],
queryFn: () => getPost(id)
},
})();
- Creating Mutations
import { useMutationBuilder } from 'tanstack-builder';
export const useCreatePost = () =>
useMutationBuilder({
prefix: "createPost",
mutationOptions: {
mutationFn: (body: CreatePostDTO) => createPost(body),
},
keysToInvalidate: ["GET_ALL_POSTS"],
})();
- Using Aliased Queries and Mutations
import React from 'react';
import { useGetAllPosts, useGetPostById, useCreatePost } from './queries';
import { DisplayPosts } from './DisplayPosts';
export function SomeComponent() {
const { getAllPostsData, getAllPostsIsLoading } = useGetAllPosts();
const { getPostByIdData, getPostByIdIsLoading } = useGetPostById(1);
const { createPostMutateAsync, createPostIsPending } = useCreatePost();
// Render components using aliased query and mutation properties
return (
<div>
{/* Display Posts Component */}
<DisplayPosts posts={getAllPostsData} isLoading={getAllPostsIsLoading} />
{/* Create Post Button */}
<button onClick={() => createPostMutateAsync({
title:'test',
body:'test'
})}
disabled={createPostIsPending}>
{createPostIsPending ? 'Creating...' : 'Create Post'}
</button>
</div>
);
}