Prithviraj Mitra
Prithviraj Mitra

Reputation: 11842

Parsing GraphQL query

I am using Gatsby (React-based framework) as CMS and trying to create a component that will return a series of JSONs.

But for some reason, there is a parsing error -

',' expected.ts(1005)

My code -

import React from "react"
import { useStaticQuery, graphql } from "gatsby"

const Carresources = () => {
  const data = useStaticQuery(graphql`
    query CarresourcesQuery {
      dataYaml {
        Carresources {
          title
        }
      }
    }
  `)
  return (
          {data.dataYaml.Carresources.map(node => (
            <script type="application/ld+json">{"@context":"https://schema.org","@type":"Car","name":{node.title}}</script>
          ))}
  )
}

export default Carresources

After the return statement, the dot before dataYaml shows the parse error. If I put any HTML code before the curly brace and after the return statement then it's fine.

Upvotes: 0

Views: 43

Answers (1)

Your module has three JavaScript/JSX syntax errors.

  1. You are trying to return a malformed JS object from the React component here:
return {data.dataYaml.Carresources.map(node => ...)}
  1. The LD-JSON script tag would be correctly defined in a HTML document but it's not valid JSX as the curly braces around the JSON object are parsed as JSX markers for interpreted content here:
<script type="application/ld+json">
  {"@context":"https://schema.org","@type":"Car","name":{node.title}}
</script>
  1. The name field of the LD-JSON object contains an invalid nested object:
{"name": {node.title}}

Here's a return statement where these syntax errors have been fixed:

  return (
    data.dataYaml.Carresources.map(node => (
      <script type="application/ld+json">
        {JSON.stringify({
          "@context": "https://schema.org",
          "@type": "Car",
          "name": node.title
        })}
      </script>
    ))
  )

Upvotes: 0

Related Questions