Created
March 18, 2024 09:06
-
-
Save BollaBerg/ca5e5fbeacfdd2630f3e17e7a0db56d6 to your computer and use it in GitHub Desktop.
Mock and read search parameters (for testing React)
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
export const mockSearchParams = (params: Record<string, string>) => { | |
const baseURL = window.location.href.split(/[?#]/)[0]; | |
const formattedParams = Object.entries(params) | |
.map(([key, value]) => `${key}=${value}`) | |
.join('&'); | |
window.history.replaceState(null, '', formattedParams ? `${baseURL}?${formattedParams}` : baseURL); | |
}; | |
export const getSearchParam = (key: string) => new URLSearchParams(window.location.search).get(key); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment