Reputation: 73
Cookie data is used in a server component to modify a fetch call.
Cooke state is modified in a client component (using js-cookie).
router.refresh() is called in the client component after the cookie state is modified.
The modified cookie state is not sent to the server in the request header.
The prior cookie state is sent instead.
The current state of the browser cookie should be sent with router.refresh()
In a context provider:
export function SelectedVehicleContextProvider({ children }: { children: ReactNode }) {
/*...*/
// If a new vehicle is selected, persist it to cookie
useEffect(() => {
if (selectedVehicle) {
const selectedVehicleString = JSON.stringify(selectedVehicle)
Cookies.set('selectedVehicle', selectedVehicleString, { expires: 365 })
} else {
Cookies.remove('selectedVehicle')
}
}, [selectedVehicle])
/*...*/
}
In a client component using the context provider:
export default function VehicleSelector({ onVehicleSelect }: { onVehicleSelect?: () => void }) {
/*...*/
setSelectedVehicle(selectedVehicleData)
router.refresh()
/*...*/
}
With that code, after router.refresh() executes, you will see an RSC request to the server and if you inspect the Request headers, you will see that the cookies value is from the previous state.
Upvotes: 0
Views: 207
Reputation: 73
I'm not really sure if this is a proper solution or not, but I discovered that adding:
router.push(currentPathname)
before
router.refresh()
caused the newly updated cookie state to be sent to the server.
Upvotes: 0