-
Hey guys. Is it possible to update configuration somehow with |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 6 replies
-
If you have a HitsPerPage widget, you can use const VirtualHitsPerPage() {
useHitsPerPage();
return null;
}
setIndexUiState({
hitsPerPage: 4
}) |
Beta Was this translation helpful? Give feedback.
-
For your second question, I just realised I misread what you're using and thought it was InstantSearch.js, but it doesn't change much about the code, so let me know if you have any issue with translating it to react, but the gist of it is:
function normalizeState(state: PlainSearchParameters) {
// these parameters are not relevant for the cache
const { page, hitsPerPage, ...rest } = state || {};
return rest;
}
const KEY = 'ais.infiniteHits';
function createCustomInfiniteHitsSessionStorageCache(): InfiniteHitsCache {
function isEqual(a: any, b: any) {
return JSON.stringify(a) === JSON.stringify(b);
}
return {
read({ state }) {
const sessionStorage =
typeof window === 'object' && window.sessionStorage;
if (!sessionStorage) {
return null;
}
try {
const cache = JSON.parse(
// @ts-expect-error JSON.parse() requires a string, but it actually accepts null, too.
sessionStorage.getItem(KEY)
);
return cache && isEqual(cache.state, normalizeState(state))
? cache.hits
: null;
} catch (error) {
if (error instanceof SyntaxError) {
try {
sessionStorage.removeItem(KEY);
} catch (err) {
// do nothing
}
}
return null;
}
},
write({ state, hits }) {
const sessionStorage =
typeof window === 'object' && window.sessionStorage;
if (!sessionStorage) {
return;
}
try {
sessionStorage.setItem(
KEY,
JSON.stringify({
state: normalizeState(state),
hits,
})
);
} catch (error) {
// do nothing
}
},
};
}
const wrapper = document.createElement('div');
container.append(wrapper);
const el = document.createElement('div');
wrapper.append(el);
const uiState = search.getUiState();
search.addWidgets([
instantsearch.connectors.connectHitsPerPage(() => {})({
items: [
{
value: 1,
label: '1',
default: (uiState.instant_search?.page! || 1) > 2,
},
{
value: 2,
label: '2',
default: (uiState.instant_search?.page! || 1) <= 2,
},
],
}),
instantsearch.widgets.infiniteHits({
container: el,
templates: {
item: '{{name}}',
},
cache: createCustomInfiniteHitsSessionStorageCache(),
}),
]);
const button = document.createElement('button');
button.textContent = 'Load more';
button.addEventListener('click', () => {
search.setUiState((state) => {
const page = state.instant_search?.page || 1;
return {
...state,
instant_search: {
...state.instant_search,
hitsPerPage: page === 1 ? 2 : 1,
page: page + 1,
},
};
});
});
wrapper.append(button); |
Beta Was this translation helpful? Give feedback.
If you have a HitsPerPage widget, you can use
setIndexUiState