I may be missing something here, but I expect the data object returned by the mutation hook below to be built in such a way that I can easily access the other properties on the object, such as response.data.login.token, etc. Instead, when I try to access the login object, Typescript tells me that I'm trying to access an object that may be undefined.
Is this the expected behavior of the hook's results?
const response = await loginMutation({
variables: {
email: "[email protected]",
password: "abc",
},
})
// Typescript no likey
console.log(response.data.login.token)
// need to use ternary or other check on response.data for Typescript to allow
// me to access login.token. Otherwise Typescript barfs.
console.log(response.data ? response.data.login.token : null)
I guess that depends on your Schema - if the mutation result data is nullable, then it makes sense to generate "nullable" types as well. Most mutations can fail, and therefore might not always return a data object.
Once optional chaining lands in Typescript (3.7), this access should be a bit cleaner.
Yeah, I'm surprised this is happening since my schema marks the result as not nullable, which is why I'm reporting it here. Here's the schema:
type Mutation {
signup(email: String!, password: String!, name: String!): AuthPayload!
login(email: String!, password: String!): AuthPayload!
}
Which plugin are you using to generate your hooks? I think it might have to do with the hooks return value including undefined due to possibly not being called / completed yet.
Hi, i think it has to do with the fact that in the past data was {}, since version three they made the update that data is initially undefined :) See https://github.com/apollographql/react-apollo/pull/3388 So the TypeScript feedback is solid, data can be undefined :)
const [doLogin, { data, loading, error }] = loginMutation({
variables: {
email: "[email protected]",
password: "abc",
},
})
if (loading) { return null; }
if (data) {
}
@maapteh is right, Apollo changed the way they pass data, and now it's optional, so the data (which is not coming from the generated output, but from apollo-client) could be undefined now. So you need to check for that before using it.
Most helpful comment
Hi, i think it has to do with the fact that in the past data was {}, since version three they made the update that data is initially undefined :) See https://github.com/apollographql/react-apollo/pull/3388 So the TypeScript feedback is solid, data can be undefined :)