I have some filters predefined and a query parameters in my URL. I need to add some other parameter to the URL to keep track of the source of the user and some other purposes. But, whenever I do a new refinement or entered into a new page(pagination). The additional parameters got deleted. How can I preserve that parameters till I go to any other routes?
Asked
Active
Viewed 543 times
1 Answers
3
In order to preserve your existing url parameters, you have to create your own URL in the router.history.
For that, grab the current location.search
and merge in the routeState
when you search or remove the routeState
object when you exit the search.
I hope the following code helps and if someone has any correction, I'm happy to hear them.
const algoliaAppId = 'APP_ID';
const algoliaApiKey = 'API_KEY';
const algoliaIndex = 'instant_search';
const search = instantsearch({
indexName: algoliaIndex,
algoliasearch(algoliaAppId, algoliaApiKey),
routing: {
router: instantsearch.routers.history({
createURL({ qsModule, location, routeState }) {
// current search params
const indexState = routeState[algoliaIndex] || {};
const { origin, pathname, hash, search } = location;
// grab current query string and convert to object
const queryParameters = qsModule.parse(search.slice(1)) || {};
// if there is an active search
if (Object.keys(indexState).length ){
// merge the search params with the current query params
Object.assign(queryParameters, routeState);
}else{
// remove the search params
delete queryParameters[algoliaIndex];
}
let queryString = qsModule.stringify(queryParameters);
if(queryString.length){
queryString = `?${queryString}`;
}
return `${origin}${pathname}${queryString}${hash}`;
},
})
}
});
search.start();

marcus
- 699
- 11
- 33