Template literal – getting error from API

The issue is that given some query like “naruto”, your current code results in the following text:

media(type:ANIME, search: naruto ) {

This is not valid syntax since String literals should be surrounded by double quotes (").

Don’t use string interpolation to provide dynamic values to the query. These should always be expressed as variables and included as a separate object inside your request alongside query.

You need to define the variable as part of your operation, providing the appropriate type

var query = `query Search ($searchQuery: String!) {

then you can use the variable anywhere inside the operation:

media(type:ANIME, search: $searchQuery) {

Now just pass the variable value along with your request.

body: JSON.stringify({
  query,
  variables: {
    searchQuery,
  }
})

Note that the variable name is prefixed with a $ inside the GraphQL document, but outside of it, we don’t do that.

Leave a Comment