How do I avoid nulls in array after delete mutation with React Relay?

106 views Asked by At

Using react-relay v15.

I have a component that gets a list of orders.

const data = useLazyLoadQuery<OrdersQueryType>(OrdersQuery, {});

I have another component that can delete orders via a mutation.

mutation DeleteOrderMutation($orderId: ID!) {
  deleteOrder(input: { orderId: $orderId }) {
    order {
      id @deleteRecord
    }
  }
}

If the data originally had three orders in it, after the mutation runs, it has 2 orders in it, and a null element where the deleted order was.

Can this be avoided so that the array only has two entries? Adding null checks for arrays contents is not ideal.

1

There are 1 answers

4
Adam Jones On

Is there a subscription set up for your original query? If configured correctly adding a subscription would dynamically update your local relay store and you would not need to manually delete the record with @deleteRecord. The following is from relay docs:

Executing a callback when the mutation completes or errors We may want to update some state in response to the mutation succeeding or failing. For example, we might want to alert the user if the mutation failed. The UseMutationConfig object can include the following fields to handle such cases: onCompleted, a callback that is executed when the mutation completes. It is passed the mutation response (stopping at fragment spread boundaries). The value passed to onCompleted is the the mutation fragment, as read out from the store, after updaters and declarative mutation directives are applied. This means that data from within unmasked fragments will not be read, and records that were deleted (e.g. by @deleteRecord) may also be null. onError, a callback that is executed when the mutation errors. It is passed the error that occurred.

I hope this helps, thanks for reading!