graphql-request
graphql-request copied to clipboard
Can't pass enum variable
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"
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
}
Currently experiencing this with enums, which are ALL_CAPS. The same request works fine with GraphiQL.
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 Did you find a way to solve this?
Same issue here. Why we cannot pass enum as variables?
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";