In my component, I am using react-adopt, to compose graphql queries and mutations, so that my render props don't get too messy. I have the following code:
This is my mutation, it takes one argument - planID.
const CREATE_ORDER_MUTATION = gql`
mutation CREATE_ORDER_MUTATION($planID: String!) {
createOrder(planID: $planID) {
planID
name
description
subscriptionType
images
subscriptionType
pricePerMonth
}
}
This is the adopt function, it takes a couple of mutations, one of which is createOrder. The way Apollo works is that I need to pass variables prop to createOrder component here. The problem is, I don't have the planID at this point. planID is available only inside of the actual component.
const Composed = adopt({
toggleCart: <Mutation mutation={TOGGLE_CART_MUTATION} />,
createOrder: <Mutation mutation={CREATE_ORDER_MUTATION} />,
});
My component looks like this. I have the planID available here, but how can I pass it as an argument to mutation?!
render() {
const { plan } = this.props;
return (
<Composed>
{({ toggleCart, createOrder }) => {
const handleAdd = () => {
toggleCart();
Router.push('/waschingmachine');
createOrder();
};
return (
<StyledPlan>
<h1>{plan.name}</h1>
<p>{plan.description}</p>
<img src={`static${plan.images[0]}`} alt="blue1" />
<h2>{plan.pricePerMonth / 100} EUR</h2>
<div className="buttons">
<Link
href={{
pathname: '/plan',
query: { id: plan.id },
}}
>
<button type="button">info</button>
</Link>
<button onClick={handleAdd} type="button">
Select Plan
</button>
</div>
</StyledPlan>
);
}}
</Composed>
);
}
If there is no way to solve it this way, how would you approach it differently?
Here is how you can pass arguments through
react-adopt
way into your inner mutations mapper:Hopefully this can be helpful to solve your issue! Just a side note, you can also get the previous
mapper
value and pass them onto the next mapper fn as part of the argument, see below:The mutate function passed in the rendered children can be called with options. Options can include variables used in the GraphQL mutation string. [1].
This means that you can call the
createOrder
mutation function like so.Given the dynamic nature of planID, there are a number of ways to implement this. One of which is to use data attributes as below:
A
data
attribute can be set on for the plan id on the button .handleAdd
can be refactored to get theplanid
from the target dataset attribute and invokecreateOrder
withplanID
variable.Another is to directly pass
planID
tohandleAdd
when calling it in theonClick
prop for the button.Then update the handler
There are tradeoffs to both approaches. For the earlier approach, the planid are set in the DOM as attributes and can be read later. While for the later one, N handlers are created for N plans and are kept in memory.