Struggling with querying child records in Salesforce

I have a Salesforce outbound message that is giving me a parent object (Cart) Id. I want to query back for all child records (Cart Items) so that I can update them. In the sample below, I just want to set the field ccrz__Price__c to 20. Below is my Job. I must be making an error but I’m not sure where. Any clues?

query(SELECT Id, ccrz__Price__c FROM ccrz__E_CartItem__c WHERE ccrz__Cart__c = ‘${state.data.Envelope.Body.notifications.Notification.sObject.Id}’`);

each(state.references[0].records[0].Id,
update(ccrz__E_CartItem__c,fields(
field(“ccrz__Price__c”, “20”)
)
)
),
update(“ccrz__E_Cart__c”, fields(
field(“Id”, dataValue(“Envelope.Body.notifications.Notification.sObject.Id”)),
field(“Pricing_Call_Status__c”, “Request Processed”)
));
`

In this case my error is "TypeError: Cannot read property ‘0’ of undefined"

It’s a bit tricky without seeing the results of the query, but “cannot read property ‘0’ of undefined” means that either state.references doesn’t exist or state.references.records doesn’t exist. What if you added a log in between the query(…) operation and the each(…) operation to see what’s coming back. Like this:

query(...); alterState(state => { console.log(state) return state; }); each(...);

That helps a lot!..I think I’m realising that my issue may actually be more fundamental than that. From adding that function earlier than the query I’m pretty happy with the output. I think where I’m actually struggling is defining a variable which can then be used to make the query (code below).

I believe that my issue might be that the variable is only assigned after the query has run. Does that sound right?

`
alterState(state => {
const cartId = state.data.Envelope.Body.notifications.Notification.sObject.Id;
console.log(‘Logs’);
console.log(‘State’);
console.log(state);
console.log(‘Cart’);
console.log(cartId);
console.log(‘Logs End’);
return state;

});

console.log(‘Run Query’);

query(SELECT Id, ccrz__Price__c FROM ccrz__E_CartItem__c WHERE ccrz__Cart__c = '${cartId}');
`

I just changed my query (see below) and I’m getting some love!

query(SELECT Id, ccrz__Price__c FROM ccrz__E_CartItem__c WHERE ccrz__Cart__c = '${state.data.Envelope.Body.notifications.Notification.sObject.Id}');

Sorry for the delay here. The issue is that “state” is the only thing that’s passed between operations. (It’s also passed between job runs if you’ve got multiple jobs chained using flow triggers, or if you’ve got a timer job—in which case each run will inherit the final state of the last run.)

If you want to define a constant during a setup operation using alterState (which is a common pattern) you’ve got to “hang it on state” like this:

alterState(state => {
state.cartId = state.data.Envelope.Body.notifications.Notification.sObject.Id;
return state;
});

query(SELECT Id, ccrz__Price__c FROM ccrz__E_CartItem__c WHERE ccrz__Cart__c = '${state.cartId}');