1.0.3 • Published 1 year ago

tanstack-builder v1.0.3

Weekly downloads
-
License
MIT
Repository
-
Last release
1 year ago

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

  1. 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)
    },
})();
  1. Creating Mutations
import { useMutationBuilder } from 'tanstack-builder';

export const useCreatePost = () =>
    useMutationBuilder({
        prefix: "createPost",
        mutationOptions: {
            mutationFn: (body: CreatePostDTO) => createPost(body),
        },
        keysToInvalidate: ["GET_ALL_POSTS"],
    })();
  1. 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>
    );
}

Authors

License

MIT

1.0.2

1 year ago

1.0.1

1 year ago

1.0.3

1 year ago

1.0.0

1 year ago