Next.js Discord

Discord Forum

'Add to favourites' functionality

Unanswered
Northeast Congo Lion posted this in #help-forum
Open in Discord
Northeast Congo LionOP
Hi, I'm trying to implement favourites functionality on my website.
Basically, the website has a catalog of cards with a :heartvercel: -buttons. All the cards that you have added to favourites are available also on a separate page (e.g. website.com/favourites).
At first I have implemented it in a similar way as in this tutorial (you don't need to watch it it's just in case my following explanation won't be clear enough) https://youtu.be/c_-b_isI4vg?t=20130 (please tell me if I can't share such links here, I'll edit the post). I just sent a corresponding fetch request (post/delete) to the server and then call router.refresh().
I call this router method because I want to be sure that if a user decide to switch from catalogue to favourites immediately, then he/she will see the most relevant information. Otherwise if I don't call router.refresh() high chances my user won't see the product he/she have just saved. Client router cash is being kept for 30 seconds (5 mins for static pages) as you may know.

Everything might seem ok, but the problem appears when I have a lot of card, so I need to scroll the page. In case I add to favourites a product at the bottom of the page router.refresh() will also reset the scroll position and turn me beck to the top. This is an extremely annoying behaviour in terms of UX.

I think it is pretty common functionality and should be simple to implement, but I'm probably missing something, because I stuck with this issue for days now. Thank you for any ideas and suggestions in advance.

4 Replies

One possible solution is to use local storage to store the scroll position before refreshing the page, and then use window.scrollTo to restore the scroll position after the page is reloaded. You can use the window.onbeforeunload event to save the scroll position, and the document.addEventListener method to read the scroll position when the page is loaded. Here is an example of how to do that in JavaScript:
document.addEventListener ("DOMContentLoaded", function (event) {
  var scrollpos = localStorage.getItem ("scrollpos");
  if (scrollpos) window.scrollTo (0, scrollpos);
});

window.onbeforeunload = function (e) {
  localStorage.setItem ("scrollpos", window.scrollY);
};
But if it is working then it is ok