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

Top comments (0)