graphql-request icon indicating copy to clipboard operation
graphql-request copied to clipboard

Can't pass enum variable

Open zlydenko opened this issue 5 years ago • 5 comments

I have SettingCreateInput! type:

{
  title: String!, 
  type: Setting!, 
  value: Json! 
}

When I'm trying to pass enum variable as string (because its only valid way in js) i got an error with "enum value expected"

zlydenko avatar Jun 27 '19 09:06 zlydenko

Hey @zlydenko I just ran into this as well, but after a little experimentation found that it seems to work with the enum as an all caps string. So "BLUE" instead of "blue". I was previously passing it as lower case and got the error you described. Can you see if that works for you as well? Might be nice to note in a doc somewhere assuming this works.

I guess this makes sense since it's the standard way to put them in the actual schema, so in my schema they would show up as:

enum Color {
  RED
  BLUE
}

worace avatar Jul 03 '19 18:07 worace

Currently experiencing this with enums, which are ALL_CAPS. The same request works fine with GraphiQL.

jottenlips avatar Nov 18 '19 17:11 jottenlips

I'm also confused about how I should be passing parametrized enums.

I'm trying to write a helper method like this:

async getDataById(id: string, type: DataType) {
  const query = gql`
    query getData($id: String!, $type: String!) {
      data(identifier: { id: $id, type: $type }) {
        id
        title
      }
    }
  `;
  return this.client.request(query, { id, type })
}

Where DataType is a string literal type. But I get an error like this:

Variable "$type" of type "String!" used in position expecting type "DataIdentifierType!".

Is there some other way I can pass the type? or do I have to define separate methods, one for each type?

goleary avatar Dec 07 '21 00:12 goleary

@goleary Did you find a way to solve this?

vinaynair39 avatar Sep 22 '22 12:09 vinaynair39

Same issue here. Why we cannot pass enum as variables?

ddoonngg avatar Sep 28 '22 01:09 ddoonngg

This is not an issue related to graphql-request, but rather to TypeScript. If you create an enum in TypesScript, the default values of its members will be a number:

enum PlainEnum { Foo, Bar }

PlainEnum.Foo; // 0
PlainEnum.Bar; // 1

If you need a string value from an enum then you will have to provide value on the right hand side of each member:

enum ValuedEnum { Foo = "FOO", Bar = "Bar" }

ValuedEnum.Foo; // "FOO"
ValuedEnum.Bar; // "Bar"

I'd recommend reading up about enums in the TypeScript handbook. That said, enums generally don't work the way you expect them to so you are likely better off using a union type:

type MyType = "foo" | "bar";

jonkoops avatar Nov 05 '23 11:11 jonkoops