Adding attributes to search hits after query and dynamically re-render in InstantSearch.js

614 Views Asked by At

I am setting up InstantSearch icw Algolia for products of a webshop with the plain JavaScript implementation. I am able to follow all the documentation, but I am running into the problem that we have prices specific to customer groups, and things like live stock information (need to do another API call for that).

These attributes I would like to ideally load after getting search results, from our own back-end.

I thought it would simply be a matter of manipulating the search results after receiving them and re-rendering only the front-end (without calling the Algolia search API again for new results).

This is a bit tricky. The transformItems functionality is possible, but I want to already display the results and load the other data into the hit templates after, not before displaying the hit results.

So I end up with a custom widget, and I can access and manipulate the results there, but here the problem is that I don’t know how to reflect these changes into the rendered templates.

The code of my widget (trying to set each stock number to 9) is as follows:

{
    render: function(data) {
        const hits = data.results.hits;

        hits.forEach(hit => {
            hit.stock = 9
        });
    }
}

The data is changed, but the generated html from the templates does not reflect any changes to the hit objects.

So how could I trigger a re-render after altering the hits data, without triggering a new search query?

I could not find a function to do this anywhere in the documentation.

Thanks!

1

There are 1 best solutions below

0
On

I don't think there is any solution beside making changes in the DOM after the render.

In this example, there is a fake id data-customer-id in the template. This information is extracted and used by the function that make the request and the DOM changes. This function is fired on the search.on('render', {}) event.

https://codesandbox.io/s/instant-search-dom-changes-after-rendering-rwdu7c