Manage your GET query parameters with a react hook
Aymeric Ratinaud
Posted on June 5, 2024
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;
๐ ๐ช ๐
๐ฉ
Aymeric Ratinaud
Posted on June 5, 2024
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
react How to build type-enforced UI components in React Native using @shopify/restyle
November 28, 2024
react Double the Talk, Double the Recording: Capturing Both Sides in Interpreted Zoom Meetings
November 27, 2024