DEV Community

Aymeric Ratinaud
Aymeric Ratinaud

Posted on

Manage your GET query parameters with a react hook

For example, if I have this query /api/couriers?status[]=READ&status[]=SENT&status[]=UNREAD&urgency.value[]=0&urgency.value[]=25&importance.value[]=50&importance.value[]=25&importance.value[]=0&category.id[]=/api/categories/17&category.id[]=/api/categories/10&direction=incoming

And I want to remove the "importance", add another filter I find this solution:

import { useState } from 'react';

const useQueryParams = (initialState = {}) => {
  const [state, setState] = useState(initialState);

  const setProperty = (key, value) => {
    setState(prevState => ({
      ...prevState,
      [key]: value,
    }));
  };

  const addElement = (key, element) => {
    setState(prevState => {
      if (!prevState.hasOwnProperty(key)) {
        return {
          ...prevState,
          [key]: [element],
        };
      }

      if (!prevState[key].includes(element)) {
        return {
          ...prevState,
          [key]: [...prevState[key], element],
        };
      }

      return prevState;
    });
  }

  const removeElement = (key, element) => {
    setState(prevState => {
      const newArray = (prevState[key] || []).filter(item => item !== element);
      if (newArray.length === 0) {
        delete prevState[key]
      } else {
        return {
          ...prevState,
          [key]: newArray,
        };
      }
    });
  };

  const clear = () => {
    setState({})
  }

  return { state, setProperty, addElement, removeElement, clear };
};

export default useQueryParams;
Enter fullscreen mode Exit fullscreen mode

Image of Datadog

The Essential Toolkit for Front-end Developers

Take a user-centric approach to front-end monitoring that evolves alongside increasingly complex frameworks and single-page applications.

Get The Kit

Top comments (0)

SurveyJS custom survey software

JavaScript UI Libraries for Surveys and Forms

SurveyJS lets you build a JSON-based form management system that integrates with any backend, giving you full control over your data and no user limits. Includes support for custom question types, skip logic, integrated CCS editor, PDF export, real-time analytics & more.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay