I have a blog front-end app built using NextJS and it looks like this:
Each card here is a functional component called
PostPreview.jsx. As you can see, each component comes with a heart icon. By default, this icon is to stay gray. However, when clicked it turns red, signifying that the post has been liked. This action only occurs if the user is logged in. If not, clicking the heart icon presents a login modal.
Right now, I’m only focussing on making the “like” persist between client-side navigations, i.e. without any interaction with the db/server.
As of now, clicking the icon, toggles the color alright. However, it fails to persist when you navigate away, say, by clicking on a post title and then hitting the back button to return to this page. What is the recommended way to achieve this functionality?
The entire codebase can be found at my repo here: https://github.com/amitschandillia/proost/tree/master/web
The code for the component in question (
PostPreview.jsx) is at: https://github.com/amitschandillia/proost/blob/master/web/components/blog/PostPreview.jsx
The site is live at https://www.schandillia.com/blog.
I understand I could use Redux, but not sure how to prevent the value from being reset upon each re-render even when using Redux.
Illustrating the problem better
Visit blog page; several instances of component (
PostPreview) render for the first time:
Receive array of post “likers” via the
Retrieve logged-in user’s ID from the Redux store via
likedBy.readersarray of IDs.
If user ID exists in
readersarray, post is liked, set
errorto turn the heart icon red and push post’s
If user ID doesn’t exist in
inheritto leave it gray and remove post’s
Like a post; click the heart icon:
errorto turn the heart icon red.
Unlike a post; click the heart icon:
inheritto turn the heart icon red.
Now click any link on page to navigate away from the page (client-side routing, no server contact here). Then hit the browser’s
back button to return to the blog page.
At this point, the component (
PostPreview) re-renders and the redux store will be reset in accordance with the original
likedBy prop object. This, of course, means that all the changes since the first render are gone. This is where I need help. How would you handle such a situation where user interactions like likes and dislikes have to be persisted across client-side navigations and also honored across re-renders?