Image not updating on refresh (src derived from state which updates correctly)
Unanswered
Carpenter wasp posted this in #help-forum
Carpenter waspOP
I have a component marked "use client". The component allows users to cycle between "today" and "tomorrow" to display an image with data related to that day from an external service.
The service has cache control "no-cache" headers in the response. When I refresh my page the following day, state is reset to "today" and the src is updated with the new date but the image from the previous day is still displayed. When I click "tomorrow" I see the correct, updated image, then when I click "today" again I see the correct, updated image. I want to see the new image on a page refresh but it seems like NextJS is serving a cached version of the image even though the src has been updated and I'm not sure how to get around it.
The date is being declared inside the component and the state (an array of two date strings) is derived from that. The src of the image is a template literal which includes a value derived from state. Here is the component:
I have tried adding a useEffect hook to force a re-render on every mount which didn't work. I don't understand why a forced re-render does not fix the image but clicking back and forth does fix it. "Empty cache and hard-reload" doesn't work either.
It's as if the component is not being re-mounted on a page refresh.
The service has cache control "no-cache" headers in the response. When I refresh my page the following day, state is reset to "today" and the src is updated with the new date but the image from the previous day is still displayed. When I click "tomorrow" I see the correct, updated image, then when I click "today" again I see the correct, updated image. I want to see the new image on a page refresh but it seems like NextJS is serving a cached version of the image even though the src has been updated and I'm not sure how to get around it.
The date is being declared inside the component and the state (an array of two date strings) is derived from that. The src of the image is a template literal which includes a value derived from state. Here is the component:
const nowPT = getPacificTimestamp()
const initialOptions = [
['Today', format(nowPT, 'yyyy-MM-dd')],
['Tomorrow', format(addDays(nowPT, 1), 'yyyy-MM-dd')],
]
const [dates, setDates] = useState(initialOptions)
const [dateIndex, setDateIndex] = useState(0)
const selectedDate = dates[dateIndex][1]
const src = `https://resource.com/images/${selectedDate}.png
const cycleDate = () => setDateIndex((prev) => (prev + 1) % dates.length)
return (
<button onClick={cycleDate}>
<Image src={src} />
</button>
)I have tried adding a useEffect hook to force a re-render on every mount which didn't work. I don't understand why a forced re-render does not fix the image but clicking back and forth does fix it. "Empty cache and hard-reload" doesn't work either.
It's as if the component is not being re-mounted on a page refresh.