Custom Query Parameters in URL #6278
-
I have a search form with two fields "JobPostingTitle" and "Location" When the user does a search using useSearchBox the "query" query param gets updated in the url and concatenates the two values together as a string. "query=senior%20oregon". This information is fine for algolia to function correctly but i would like to also store additional information in the url like so "query=senior%20oregon&JobPostingTitle=senior&Location=oregon" That way i can pre-populate my form with "JobPostingTitle" or "Location" if someone ever decides to share the url. I started to explore routing prop with custom state mapping. My thought was when a user fills out my form i can update the queryParams that i'm holding in useState and pass that on to my stateToRoute function. Although this didn't seem to work as i expected bc stateToRoute function doesn't get access to state changes that happen to queryParams. queryParams in stateToRoute remain unchanged as {} even if i call the setQueryParams function. const [queryParams, setQueryParams] = useState({});
return (
<JobSearchProvider {...props}>
<InstantSearch
searchClient={searchClient}
indexName="example"
future={{
preserveSharedStateOnUnmount: true,
cleanUrlOnDispose: false,
}}
routing={{
router: history({
cleanUrlOnDispose: false,
}),
stateMapping: {
stateToRoute(uiState) {
const state = uiState['example'];
console.log(queryParams); // {JobPostingTitle: 'senior', Location: 'oregon'}
return {
...state,
...queryParams,
};
},
routeToState(routeState) {
return {
['example']: {
...routeState,
},
};
},
},
}} |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
What I recommend is the following:
const routing = {
stateMapping: {
stateToRoute(uiState) {
const existingParameters = new URLSearchParams(window.location.search);
return {
...uiState['example'],
JobPostingTitle: existingParameters.get('JobPostingTitle'),
Location: existingParameters.get('Location'),
};
},
routeToState({ JobPostingTitle, Location, ...routeState }) {
return {
['example']: routeState,
};
},
},
}; Then later when you update the JobPosting or Location, you can do |
Beta Was this translation helpful? Give feedback.
What I recommend is the following:
Then later when you update the JobPosting or Location, you can do
history.pushState
…