GraphQL gql Syntax Error: Expected Name, found } - syntax-error

I'm attempting to set up Apollo GraphQL support in a new React project, but when I try to compile a query using gql I keep receiving the error:
Syntax Error: Expected Name, found }
This is generated by the following code:
import gql from 'graphql-tag'
const query = gql`
{
user(id: 5) {
firstName
lastName
}
}
`
console.log(query)
I'm basing this code off the example code found here: https://github.com/apollographql/graphql-tag
What is the Name referred to in the error message? Does anyone know what I'm doing wrong here?

This error occurs mostly when there are unclosed curly braces or when some fields are not properly defined while calling the query.

The accepted answer didn't solve my issue. Instead, it worked if you remove the initial curly brackets.
The query should look like this instead:
const query=gql`
user(id: 5) {
firstName
lastName
}
`

The causes could be:
you are adding a "()" at the beginning for no reason
you need to add more 'nested' parameters.
Especially if you are using an online GraphiQL editor. Examples:
1- Wrong code (extra parenthesis)
{
allFilms() {
films {
title
}
}
}
2- Wrong code (more parameters need it eg: title)
{
allFilms {
films {
}
}
}
3- Correct code
{
allFilms {
films {
title
}
}
}

GraphQLError: Syntax Error: Expected Name, found "$".
One more example of a similar error (For other users).
theErrorIsHere (Could be extra ( or { before the $varName) added before $speakerId
Error code:
const FEATURED_SPEAKER = gql`
mutation markFeatured($speakerId: ID!, $featured: Boolean!){
markFeatured(speaker_id: theErrorIsHere$speakerId , featured: $featured){
id
featured
}
}
`;
Correct code:
const FEATURED_SPEAKER = gql`
mutation markFeatured($speakerId: ID!, $featured: Boolean!){
markFeatured(speaker_id: $speakerId , featured: $featured){
id
featured
}
}
`;

I'm not 100% sure what the root of my problem was, but moving all the query code into a separate es6 module fixed the issue. There must have been some kind of contamination from the surrounding code. For reference my query was embedded within a React component.
This works:
import gql from 'graphql-tag'
const query = gql`
{
user(id: 5) {
firstName
lastName
}
}
`
export default query

Another cause for this error: you are referencing a type that is defined further down. Move the type you are referencing up.
For example:
type Launch {
rocket: Rocket
}
type Rocket {
name: String
}
will throw an error, as Launch references Rocket before Rocket is defined.
The corrected code:
type Rocket {
name: String
}
type Launch {
rocket: Rocket
}

In my case, I got the error simply because I'm adding : which I shouldn't have done.
e.g:
const query = `
query($id: String!) {
getUser(id: $id) {
user: {
id
name
email
createdAt
}
}
}
`
If you pay close attention to line 4 of the code above you'll realize that I added : after the user before the curly brace, then I began to list the user's data I wanna query and THAT WAS EXACTLY WHERE THE ERROR WAS!
Removing the : solve the issue!
It should be:
user {
id
name
...
}

In NestJS framework, this error happened to me because I defiled GraphQL field in my schema.graphql file as:
lastUpdated(): Date
Instead it should be just
lastUpdated: Date
(it doesn't take any argument)

I was receiving a similar error server side:
GraphQLError: Syntax Error: Expected Name, found ]
I realized the cause in my case was a type definition with an empty array.
This breaks:
type Settings {
requires: []
}
But this works:
type Settings {
requires: [String]
}

I had this problem and the cause was a string value with double-quotes inside double-quotes, like so: "this "is" bad".

In my case I got the error because of the following:
const GET_POSTS_OF_AUTHOR = gql`
query GetPostsOfAuthor($authorId: Int!) {
postsOf($authorId: Int!) {
id
title
}
}
`;
When it should have been:
const GET_POSTS_OF_AUTHOR = gql`
query GetPostsOfAuthor($authorId: Int!) {
postsOf(authorId: $authorId) {
id
title
}
}
`;
erroneously thought $authorId passed through identically to the function call instead of setting a property inside the function call.

This can happen if you use gql from #clinet/apollo and in the backticks you try to inject dynamic js value. Remove it and replace with normal scalar and it will fix your issue.
example:
${SOME_MAX_VALUE} -> 20

On ny side the error was caused by extra {} Curly braces. Solved by just removing them.

I was getting the same error. In my case putting the id inside double quote solved the issue as the type of id required string value.
{
product(id: "${id}") {
name
}
}

Posting here in case anyone else had this problem but you also get this error if you accidentally make your query look like json with colons (:).
ex:
data {
property {
key: {
deepKey
}
}
}
will give the same error from GQL compile

Related

Return selected fields only React Native / GraphQL / Amplify

I have the following basic list query in GraphQL:
API.graphql(graphqlOperation(listSomething,{filter: filter})).then(({ data: { something } }) => {
// Returns the entire object
})
This will return an array containing entire objects, but as I've seen on multiple GraphQL tutorials, I'd like to take advantage of the utility of only returning / plucking select fields for obvious reasons. However there isn't a lot of information out there on GraphQL + RN + Amplify. So how would I re-write this query to only return the attribute id for instance? Or is that something that I have to define as a resolver in the graphql / queries.js file? I'm using autogenerated queries so it sort of feels like an anti-pattern to add your own queries to that file — Correct me if I'm wrong.
Thanks!
I'm still at an early stage of getting familiar with AWS, so please take this with a grain of salt.
Your auto generated queries.js will contain a listSomething query, that looks something like this:
export const listTodos = /* GraphQL */ `
query ListTodos(
$filter: ModelTodoFilterInput
$limit: Int
$nextToken: String
) {
listTodos(filter: $filter, limit: $limit, nextToken: $nextToken) {
items {
id
userID
name
description
createdAt
updatedAt
}
nextToken
}
}
`;
I created a new folder called /src/customGraphQL and created a file called customListTodos.js. I copied there the auto generated query, changed the query name, and removed the fields I didn't need.
export const customListTodos = /* GraphQL */ `
query CustomListTodos(
$filter: ModelTodoFilterInput
$limit: Int
$nextToken: String
) {
listTodos(filter: $filter, limit: $limit, nextToken: $nextToken) {
items {
name
description
}
nextToken
}
}
`;
I only changed the query's name, but kept the inner function's name as listTodos, so I'm running a customised version of that query. If the original API is pushed to AWS, you can import and use the custom query:
import {customListTodos} from './src/customGraphQL/customListTodos';
...
API.graphql(graphqlOperation(customListTodos ...
This worked for me. Making a custom queries file was pretty simple and I was able to limit the object to just returning the _version.
export const getUserVersion = /* GraphQL */ `
query GetUserVersion($id: ID!) {
getUser(id: $id) {
_version
}
}
`;
Then in my .js file I could call the function this way:
const getUserVersionResponse = await API.graphql(
graphqlOperation(getUserVersion, { id })
);

Difficulty parsing JSON 3 levels deep

React native is having difficulties parsing JSON three levels deep. The object is structured like so:
data: {
post: {
user1: {
name: "user name"
}
}
}
data.post.user1 works fine and returns an object; however, when I try to get the name parameter react-native throws the following error:
undefined is not an object (evaluating 'data.post.user1.name')
Is this a known issue? I am getting data from response.json in a fetch call. EDIT: Object.keys(data.post.user1) returns the same error.
First, declare it in a variable and then make an object :
const data = {
date:{
post: {
user1: {
name: "user name"
}
}}}
Get the value like this :
<Text>{data.date.post.user1.name}</Text>

pass variable into GraphQL query in Gridsome/Vue.js

I have a Vue.js app running with a GraphQL backend, and Gridsome as the Vue.js boilerplate generator.
I'm trying to write a GraphQL query to only return the data of the logged in user, like this :
query Blah($test: String!) {
db {
settings (where: {user_id: {_eq: $test}})
{
key
value
}
}
with the $test variable defined here:
export default {
data() {
return {
test: "Va123",
user: null
};
}
}
But I get this error message:
An error occurred while executing query for src/pages/Profile.vue
Error: Variable "$test" of required type "String!" was not provided.
This is for a Girdsome page, not a template
It looks like the only way is to create pages programmatically using createPage() and pass the page context variable down the the page-query.
https://gridsome.org/docs/pages-api/#the-page-context

VueJs - using template strings inside the data function returns undefined

When I'm trying to use Template strings inside the data function in vuejs but, it always returns undefined any idea how to solve this ?
I was trying to make a URL for an API call dynamic
Cheers,
data() {
return {
baseUrl: `https://example.com/api/json?key=${this.key}`,
key: "IzNDU2Nzg5MDEyMzQ1Njc"
};
}
This is a JavaScript issue. If you run the following simple example in JavaScript you'll get a "is not defined" error (when running in strict mode).
{ a: `${b}`, b: "123" }
> VM246:1 Uncaught ReferenceError: b is not defined
You can't reference an adjacent variable ('key' in your example) in an object literal declaration.
You can use a Vue.je computed property for baseURL:
computed: {
baseUrl() {
return `https://example.com/api/json?key=${this.key}`;
}
}
The data property cannot be made dynamic. Use a computed property like below:
computed: {
baseUrl() {
return `https://example.com/api/json?key=${this.key}`
}
}

var within firebase set

I am trying to create some dynamic JSON based on a value of a name like below
this.merchantFirebase.child(firebase.auth().currentUser.uid).update({
this.props.data.name: {
status: this.state.productSwitch
}
});
I was thinking this would create something like
this.merchantFirebase.child(firebase.auth().currentUser.uid).update({
latte: {
status: this.state.productSwitch
}
});
but it is just given me an error of unexpected token
You'll need to use a different notation for this:
var updates = {};
updates[this.props.data.name] = { status: this.state.productSwitch };
this.merchantFirebase.child(firebase.auth().currentUser.uid).update(updates);
By using square-bracket notation, JavaScript "knows" that it needs to evaluate this.props.data.name as an expression, instead of using it as the literal name of the property (as it tries to do in your code).