@cgarciagarcia/react-query-builder
TypeScript icon, indicating that this package has built-in type declarations

1.13.0 • Public • Published

TypeScript React hook query Builder provides a way to build a query string compatible with spatie/laravel-query-builder.

Coverage Status Test CI License: MIT Codacy Badge

Installation

You can install package using yarn (or npm):

yarn add @cgarciagarcia/react-query-builder

Usage

This package is designed to provide an easy way to interact with the backend integration of spatie/laravel-query-builder using your favorite frontend library, React.js. It includes a custom hook that you can use for seamless interaction.

Some Examples

Here is a simple example:

import { useQueryBuilder } from "@cgarciagarcia/react-query-builder";

const baseConfig = {
  aliases: {
    "frontend_name": "backend_name",
  },
 
}

const builder = useQueryBuilder(baseConfig)

builder
  .fields('user.name', 'user.last_name', 'other')
  .filter("age", 18)
  .sort("created_at") // by default sorting asc
  .sort("age", 'desc') // sorting desc
  .setParam("external_param", 123) // you can define it in the baseConfig
  .include("posts", "comments")

function apiCall() {
  console.log(builder.build());
  // ?fields[user]=name,fields=other,last_name&filter[age]=18&sort=created_at,-age&includes=posts,comments
  return fetch("https://myapi.com/api/users" + builder.build()).then(response => response.json())
}

Configurations

You can set the initial state for your query builder, also it's possible to modify the delimiter for each action (fields, filters, includes, sorts), the global delimiter will be overwritten with the specific delimiter

// Default configuration 
const baseConfig = {
  aliases: {},
  filters: [],
  includes: [],
  sorts: [],
  fields: [],
  pruneConflictingFilters: {},
  delimiters: {
    global: ',',
    fields: null,
    filters: null,
    sorts: null,
    includes: null,
    params: null,
  },
  useQuestionMark: false,
  params: {}
}

Remove Methods

You can use the remove method in sort, includes, filter like this:
const builder = useQueryBuilder(baseConfig)

  builder
    .removeField('field_1', 'field_2')
    .removeFilter('name', 'last_name')
    .removeSort('name', 'id')
    .removeInclude('address', 'documents')
    .removeParam('param1', 'param2')

Clear Methods

You can use the clear methods for delete the entire data group

const builder = useQueryBuilder(baseConfig)

  builder
    .clearFields()
    .clearFilters()
    .clearIncludes()
    .clearSorts()
    .clearParams()

Filters that don't work together

Maybe your business logic has filters that won't work together, for example you could have filters like date filter and between_dates filter in your backend, but you can not filter by both at the same time, so you have to be sure to clear incompatibles filters before to adding a new one. With this purpose the property pruneConflictingFilters was created, you can define these incompatibilities in the base configuration and delegate the humdrum action to the library.

Example:

const builder = useQueryBuilder({
  pruneConflictingFilters: {
    date: ['between_dates']
  },
})

builder.filter('date', today)
    .build() // the result is ?filter[date]=2024-08-13
    .filter('between_dates', [lastWeek, today])
    .build() // the result in this line is ?filter[between_dates]=2024-08-06,2024-08-13

How does it work?

When you define that date filter is not compatible with between_dates, internally the library define the bidirectional incompatibility for you. Too much magic? Don't worry, you still could define manually the inverse incompatibility to have explicit declaration from your side.

Utilities

You could use the builder with your Tank Stack React query implementation for example:

toArray()

import { getApiUsers } from "@/Api/users"
import { useQueryBuilder } from "@cgarciagarcia/react-query-builder";

const MyComponent = () => {

  const builder = useQueryBuilder()

  const useUserQuery = useQuery({
    fnQuery: () => getApiUsers(builder),
    queryKey: ['userQuery', ...builder.toArray()]
  })

  /* Rest of code */
}

when()

import { getApiUsers } from "@/Api/users"
import { useQueryBuilder } from "@cgarciagarcia/react-query-builder";

const MyComponent = () => {
  
  const builder = useQueryBuilder()

  const useUserQuery = useQuery({
    fnQuery: () => getApiUsers(builder),
    queryKey: ['userQuery', ...builder.toArray()]
  })
  
  const onClickButton = (id: number|null) => {
    
    builder.when(id !== null, (state) => {
      console.log(state) // reveal internal state
    })
  }
  
  /* Rest of code */
}

Next features

  • Interaction with url query params

Consider supporting me

I invite you to support its creator. Your contribution will not only help maintain and improve this package but also promote the continuous development of quality tools and resources. You can also email me and let me know.

Paypal: @carlosgarciadev

License

The MIT License (MIT). Please see License File for more information.

Package Sidebar

Install

npm i @cgarciagarcia/react-query-builder

Weekly Downloads

62

Version

1.13.0

License

MIT

Unpacked Size

71.4 kB

Total Files

22

Last publish

Collaborators

  • cgarciagarcia