Next.js Discord

Discord Forum

Best way to update specific item in fetched list

Unanswered
Largehead hairtail posted this in #help-forum
Open in Discord
Largehead hairtailOP
I'm fetching and rendering an array of products coming from an external API (through fetch api and server actions), I have an edit component for this product and I need to make it so that when the user confirms the changes, the product is updated in real time on the screen

I could use revalidatePath, for example: revalidatePath(/products/fetch?page=${pageOfItem}) after the modification request, but this would refetch all items with this page number in my database, not just the that I changed, so it might be an unnecessary process, I don't know

another way would be to make the listing component like 'use client' and save the products in a state when they are fetched, that way I could update only what needs to be updated

which approach would be best?

7 Replies

your second option (the ’use client’ option) is the optimal approach imo… especially since you’re wanting the data change to be reflected in real time on the user’s end. this is, to my understanding, essentially the main purpose of client components.
@clarity your second option (the `’use client’` option) is the optimal approach imo… especially since you’re wanting the data change to be reflected in real time on the user’s end. this is, to my understanding, essentially the main purpose of client components.
Largehead hairtailOP
hmm, I just found a problem with this option, if I refresh the page, it shows the product before updating (as the items are cached), but I didn't want to disable the cache
the ideal way I can think of would be to revalidate/refetch only the updated item, or somehow change the cached data of that item in there manually
but I can't think of how to do this
OHHH, i see what you're saying

maybe you could apply some logic that utilizes local storage. store/alter specific parts of the data from there, and reflect those changes to the user by altering the state of it with useState()?
Largehead hairtailOP
do you say to store the changes in local storage and apply them to the state when the page loads?
Largehead hairtailOP
in the worst-case scenario, I can cache products in backend and disable fetch api storing data
in the backend I can have greater control over the cache when the product is edited, and as I'm using nestjs it shouldn't be that difficult