Why does return literals in the handler create `TypeError: Expected a semicolon`?

77 Views Asked by At

Here is my workable index.tsx route:

import { Handlers, PageProps } from "$fresh/server.ts";

export const handler: Handlers<Data> = {
  GET(req, ctx) {
    const a = 'hello'
    return ctx.render({ a })
  },
};

export default function Home({ data }: PageProps<Data>) {
  return (
    <>
      {JSON.stringify(data) } 
    </>
  );
}

However if I change the handler from:

const a = 'hello'
return ctx.render({ a })

to:

return ctx.render({ 'hello' })

I get this error:

error: Uncaught (in promise) TypeError: Expected a semicolon at file:///D:/QC%20supplements/Code/Apps/trankyweb/routes/index.tsx:24:33

      return ctx.render({ 'hello' })
                                  ~
  const manifest = (await import(toFileUrl(join(dir, "fresh.gen.ts")).href))
                    ^
    at async dev (https://deno.land/x/[email protected]/src/dev/dev_command.ts:38:21)
    at async file:///D:/QC%20supplements/Code/Apps/trankyweb/dev.ts:5:1
Watcher Process failed. Restarting on file change...

What does this mean? I read SyntaxError: missing ; before statement - JavaScript | MDN but I don't see how it's applying to this.

The fresh.gen.ts file is automatically generated. Here is the content of dev.ts:

#!/usr/bin/env -S deno run -A --watch=static/,routes/

import dev from "$fresh/dev.ts";

await dev(import.meta.url, "./main.ts");
1

There are 1 best solutions below

7
On BEST ANSWER

because ctx.render() expects object: {a} is equivalent to {a: value of a}. This is not jsx templating that u think u are using, this is function call that expects object. By providing string literal we cant know which is the key and which is the value, it would be invalid es6 shorthand syntax for object initialization.

a='asd'
const obj = {a}

obj is {a: 'asd'}

providint only string literal in initializer however is invalid es6 shorthand sybtax. Because ctx.render is function call it does not expect jsx templating syntax, but object