Next.js Discord

Discord Forum

Better solution to revalidating data when a user clicks a button?

Answered
Netherland Dwarf posted this in #help-forum
Open in Discord
Netherland DwarfOP
This is a straight forward question and I frankly don't know why I haven't asked earlier,

I have a page which renders the current users inbox, the inbox renders all conversations and they are cached using unstable_cache to help load times. Each of these conversations can be clicked to and redirected to the overview of the conversation itself. When the conversation page is loaded, I have a function that marks the conversation as read if it is marked unread in the database

Now, this is a simple approach and it works. However, my issue arises because I have a button in that component that basically allows the user to mark the conversation read/unread if they so desire. This is a action called from a client component, this action basically updates the conversations read status as needed. But, I need to revalidate the inbox when this has been updated so the inboxs conversation can reflect the new changes. The issue is, because I run revalidateTag this causes a re-render which in return calls the function that marks the conversation as read.

At first, I considered why not call revalidateTag in the server component, ended up getting an error because you can only call that from server actions or route handlers. So the next best idea, store a temporary cookie that checkes whether this page was loaded from a re-render or this is the user going to the page the first time. If its the user going to the page the first time, I had a route that automatically revalidated inbox. This solution was great, worked perfectly on my dev enviroment until I tried to test this on a production to see if this would make a difference. It did.. I still have no clue why, but for some reason I had to click the conversation TWICE before mark this as read and it would call the route to revalidate the data. This solution also seemed to run everything twice, for example I had a console.log on the route that was logged twice.

I need a better approach to this because I'm losing my mind!
Answered by Netherland Dwarf
Turns out, using revalidateTag causes the page to be re-rendered, my approach was to have an api route that is called in a useEffect revalidating the data
View full answer

4 Replies

Netherland DwarfOP
omg
finally
Netherland DwarfOP
Turns out, using revalidateTag causes the page to be re-rendered, my approach was to have an api route that is called in a useEffect revalidating the data
Answer
Netherland DwarfOP