Greg Forel
Greg Forel

Reputation: 2559

Expected type variable to be an object using Apollo

I have a working query in GraphQL Playground that I'm trying to get to work using Apollo. I can't seem to pass a variable properly to the query.

Here's my code:

public render() {
  const CONVERSATION = gql`
    query GetConversation(
      $conversationId: ConversationWhereUniqueInput!
    ) {
      conversation(where: $conversationId) {
        id
        title            
      }
    }
  `
  const conversationId: any = this.props.conversation
  console.log(conversationId) // works.

  return (
    <ApolloProvider client={this.client}>
      <div>
        <Query query={CONVERSATION} variables={{ conversationId }}>
          {({ loading, error, data }) => {
            if (error) {
              return <div>${JSON.stringify(error)}</div>
            }
            if (loading) {
              return <div>Loading...</div>
            }
            return <div>{JSON.stringify(data)}</div>
          }}
        </Query>
      </div>          
    </ApolloProvider>
  )
}

The error message I get is:

${"graphQLErrors":[],"networkError":{"name":"ServerError","response":{},"statusCode":400,"result":{"errors":[{"message":"Variable \"$conversationId\" got invalid value \"cjrtfagwc00bq0a300njz594r\"; Expected type ConversationWhereUniqueInput to be an object.","locations":[{"line":1,"column":23}]}]}},"message":"Network error: Response not successful: Received status code 400"}

[GraphQL error]: Message: Variable "$conversationId" got invalid value "cjrtfagwc00bq0a300njz594r"; Expected type ConversationWhereUniqueInput to be an object., Location: [object Object], Path: undefined

I thought that by passing my variable as variables={{ conversationId }} I was actually passing an object as requested. What am I doing wrong?

EDIT Benjie helped me find what was wrong.

I just had to change const conversationId: any = this.props.conversation to const conversationId: any = { this.props.conversation }

Upvotes: 0

Views: 4242

Answers (1)

Benjie
Benjie

Reputation: 7946

You are passing the variables:

{
  "conversationId": "cjrtfagwc00bq0a300njz594r"
}

This is fine. The problem is that your query is defined stating that the conversationId variable (which you have given the string (or ID?) value "cjrtfagwc00bq0a300njz594r") should be a ConversationWhereUniqueInput (which is an input object):

$conversationId: ConversationWhereUniqueInput!

These two types (ID and ConversationWhereUniqueInput) are not compatible.

Given your variable naming, I suspect you want to change your GraphQL query so that it passes the conversationId property as part of the where argument:

query GetConversation(
  $conversationId: ID!
) {
  conversation(where: {conversationId: $conversationId}) {
    id
    title            
  }
}

Upvotes: 2

Related Questions