Last active
December 6, 2024 23:23
-
-
Save natanfeitosa/83344c7efe6238ec8eb5435f9f2c5445 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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