Apollo GraphQL: How to Insert Mutated Object at Correct Index in Existing Array?

314 views Asked by At

I've got a subscriptionObserver including the following:

return update(
    previousResult,
    {
        ApptsForCurrentUser: {
            $push: [newAppt],
        },
    }
);

The new item that arrives via the subscription needs to be inserted into the ApptsForCurrentUser array in date-sorted order. It's a multi-dimensional array, and I can sort it using an $apply function.

Is there syntax to $push newAppt to the array prior to handing the array off to the $apply function that will sort it?

Alternatively, should I do something like this?

(Not yet tested):

var newResult = clonedeep(previousResult);  //lodash
newResult.push(newAppt);
newResult.sort(myCustomSortFunction);
const newResultAsAConst = clonedeep(newResult); 
return update(
    previousResult, newResultAsAConst
);
1

There are 1 answers

0
VikR On BEST ANSWER

Building on advice from @Sacha, I was able to solve this via this code:

import update from 'immutability-helper';
[.....]

const resultWithNewApptAdded = update(previousResult, {getAllApptsForCurrentUser: {$push: [newAppt]}});
//getAllApptsForCurrentUser contains unsorted list of appts
resultWithNewApptAdded.getAllApptsForCurrentUser = resultWithNewApptAdded.getAllApptsForCurrentUser.sort(mySortFunction);
return resultWithNewApptAdded;