Skip to content

Instantly share code, notes, and snippets.

@natanfeitosa
Last active December 6, 2024 23:23
Show Gist options
  • Save natanfeitosa/83344c7efe6238ec8eb5435f9f2c5445 to your computer and use it in GitHub Desktop.
Save natanfeitosa/83344c7efe6238ec8eb5435f9f2c5445 to your computer and use it in GitHub Desktop.
import { useState, useEffect } from 'react';
export default function useSearchParams() {
const getSearchParams = () => {
const queryString = window.location.search;
return new URLSearchParams(queryString);
};
const [searchParams, setSearchParams] = useState(getSearchParams);
useEffect(() => {
const handlePopState = () => {
setSearchParams(getSearchParams());
};
window.addEventListener('popstate', handlePopState);
return () => {
window.removeEventListener('popstate', handlePopState);
};
}, []);
const setCustomSearchParams = (newParams) => {
const updatedSearchParams = new URLSearchParams(window.location.search);
Object.keys(newParams).forEach((key) => {
if (newParams[key] === null) {
updatedSearchParams.delete(key);
} else {
updatedSearchParams.set(key, newParams[key]);
}
});
window.history.pushState({}, '', `${window.location.pathname}?${updatedSearchParams.toString()}`);
setSearchParams(updatedSearchParams);
};
return [searchParams, setCustomSearchParams];
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment