Hello I'm making a comment section on my website but I don't want to fetch all of the comments from my database when someone refreshes the page I want to solve this problem by storing comments in the array but when I use
export const comments = writable(localStorage.getItem("comments") || []);
it doesn't create an array in my local storage is there even a way to store an array in local storage with svelte or should I handle this problem differently?
If you want to store something in localstorage user:
localstorage.setItem('comments', JSON.stringify(arr_of_cmnts);
Now, let's assume when your page opens you check if your localstorage has comments by using something like:
//In svelte
let arr_of_cmnts = [];
export const comments = writable(localStorage.getItem('comments')|| JSON.stringify(arr_of_cmnts));
//js **normally**
const cmnts = JSON.parse(localstorage.getItem('comments'));
if(cmnts && cmnts.length > 0)
//use this array
else
//call server to get comnts and store them in localstorage
In the if block how do you know if comments in localstorage are the latest??? Maybe someone has put a new comment from the last time you visited.
There maybe some solutions to this, like you inquiring db for latest comments timestamp and then checking whether the stored comments are stale or not. Another approach of the issue (not having to query your db always) is to use a Cache (redis maybe), to serve comments, and whenever someone writes a new comment, along with updating db you can update your cache as well. This makes read request faster.