docs icon indicating copy to clipboard operation
docs copied to clipboard

On-demand Rendering Adapters @ Cookies examples are not working - Correct implementation provided

Open Kodalem opened this issue 1 year ago • 1 comments

📚 Subject area/topic

On-demand Rendering Adapters @ Cookies

📋 Page(s) affected (or suggested, for new content)

https://docs.astro.build/en/guides/server-side-rendering/#cookies https://docs.astro.build/en/reference/api-reference/#set

📋 Description of content that is out-of-date or incorrect

Given example does not work anymore and is likely due to being outdated, because the Astro.cookies.set("counter",counter) accepts types key: string, value: string | Record<string, any>, options?: AstroCookieSetOptions instead of (key: string, value: string | number | boolean | object, options?: CookieSetOptions) => void. Example works only for npm run dev, but fails with npm run build with TypeScript error 2345.

Also to note, there's also TypeScript error 2532, as the cookie value in const cookie = Astro.cookies.get("counter") might be undefined and fixed with !. parameter like so const cookie = Astro.cookies!.get("counter").

Broken example:

---
let counter = 0

if (Astro.cookies.has("counter")) {
  const cookie = Astro.cookies.get("counter")
  counter = cookie.number() + 1
}

Astro.cookies.set("counter",counter)
---
<html>
  <h1>Counter = {counter}</h1>
</html>

Working basic example using Record type, compiles without error nor warnings.

---
// Create the Record Type
interface CookieData {
   exampleString: string;
   counter: number;
}
// Create the Example Data
let CookieDataExample: CookieData = {
   exampleString: "example",
   counter: 0,
}
let counterFromCookie = -1

if (Astro.cookies.has("counter")) {
	console.log("cookie exists")
    const cookie = Astro.cookies.get("counter")
	// Parse as JSON data and get the counter value
	console.log(cookie!.json())
	counterFromCookie = cookie!.json().counter
	CookieDataExample.counter = counterFromCookie + 1
}
Astro.cookies.set("counter", CookieDataExample)
---
<html>
  <h1>Counter = {CookieDataExample.counter}</h1>
</html>

🖥️ Reproduction in StackBlitz (if reporting incorrect content or code samples)

No response

Kodalem avatar Jun 20 '24 17:06 Kodalem