I'm having trouble with a seemingly trivial use-case:
Assume there is a large checkout page with a 'coupon' field and an 'apply' button next to it. The user enters a coupon code and presses 'apply' expecting the coupon code to be applied to his purchase.
This is the GraphQL schema:
type Query {
coupon(code: String!): Coupon!
}
type Coupon {
id: ID!
code: String!
discountPercentage: Float!
isValid: Boolean!
}
The basic flow is like this:
- User enters coupon code and presses 'apply'
- Client fetches the coupon code from the backend
- If the coupon is valid, a message with the discount is displayed, or an error message.
- A
dispatch
function is called to change the context of the checkout page.
I'm relatively new to Relay and trying to understand how this can be properly handled. It would be straightforward to achieve with Apollo by manually triggering the query and waiting for the result. Relay seems to force an approach where only mutations can be triggered on user events and queries can't be called imperatively.
I'm currently exploring using commitMutation
with a query instead of a mutation, which feels like a hack:
commitMutation(environment, {
mutation: query, // provide a query instead of a mutation
variables: {
code: value, // provide the coupon code as variable
},
onCompleted: (response, errors) => {
setLoading(false)
if (response.coupon.isValid) {
// ...
} else {
// ...
}
},
onError: () => {
// ...
},
})
What is the proper way to handle such a scenario?