InstantSearch Js add to favourites ajax sync

Hi, I’m using Laravel & InstantSearch Js for my search.

I’m hoping for some help with something very common which is favouriting items in my search.

I’ve set up the backend of my website correctly for, ajax calls to be made to favourite or unfavorite an item in my search (which works) I just can’t visually display this to my users, they have to refresh the page entirely before it is indicated that the particular item has been favourited.

I’m storing the ids of the users favourited items in a Javascript array, I’m then loading a conditional hits template for the search results depending on if that item is favourited or not (if the item is favourited a button displays saying “remove from favourites” and if the item is favourited a button displays saying “add to favourites”).

Once a user favourites a profile I’m trying to use ajax to retrieve the updated array of ids and then refresh the search but it appears that trying to call search.refresh(); has no affect.

I’d really appreciate some help with this, maybe there is a better way than what I’m doing.

Thanks in advance for any help.

Hi there,
Thanks for reaching out to us.

First of all, the reason why search.refresh() did nothing is because even though you called it, the search result returned from Algolia stays the same. So it skips re-rendering.

The only change is the list of ids from your server. So calling refresh() won’t help in this case.

What I recommend is not to re-render whole components but to manipulate each dom at a time.

In this example, there is a set named favoriteObjectIds. It contains a list of objectIDs that are in favorites. Whenever add or remove button is clicked, the list changes and it toggles the class name on the hit.

Let me know how it goes and if you have any question.
Have a nice day!

1 Like

5-hours

Thank you so much this works perfectly!

Only note is that in the CodePen example when const objectId = elem.getAttribute('data-object-id'); is used the data attribute “object id” is on the parent, not the button so this would need to be const objectId = elem.parentElement.getAttribute('data-object-id');

My bad. I’ve updated the example.
Thanks for letting me know :slight_smile: