constructing link with search parameters

So I have a navbar that links to a /results page. The situation is that if a user has preferences saved in localstorage, i want to embed those preferences within the link as search params like /results?sports=true&... currently, i have
const appendParams = (path: PagePaths): PagePaths => {
const searchParams = new URLSearchParams();

defaultPreferences.forEach((pref) => {
searchParams.append(pref, "true");
});

return `${path}?${searchParams.toString()}` as PagePaths;
};

const pages: Record<string, PageLink> = {
home: { title: "Home", href: "/" },
search: { title: "New Preferences", href: "/search" },
results: {
title: "Default Preferences",
href: appendParams("/results"),
},
};

useEffect(() => {
const savedPreferencesOrEmpty = localStorage.getItem("preferences") ?? "[]";

setDefaultPreferences(() => JSON.parse(savedPreferencesOrEmpty));
}, []);
const appendParams = (path: PagePaths): PagePaths => {
const searchParams = new URLSearchParams();

defaultPreferences.forEach((pref) => {
searchParams.append(pref, "true");
});

return `${path}?${searchParams.toString()}` as PagePaths;
};

const pages: Record<string, PageLink> = {
home: { title: "Home", href: "/" },
search: { title: "New Preferences", href: "/search" },
results: {
title: "Default Preferences",
href: appendParams("/results"),
},
};

useEffect(() => {
const savedPreferencesOrEmpty = localStorage.getItem("preferences") ?? "[]";

setDefaultPreferences(() => JSON.parse(savedPreferencesOrEmpty));
}, []);
, which i think? will work. but i feel like this is hacky and not really the right way to handle it (primary concern is the appendParams function. any thoughts? originally i was going to construct a URL object and use the searchParams.append method on the object to add the params, but next's router doesn't have a function that returns the actual, non-relative, base path
0 Replies
No replies yetBe the first to reply to this messageJoin
Want results from more Discord servers?
Add your server