😎 Discover cool tips and tricks for customization in our next Developer Deep Dive virtual event - sign up now!

Mutations API - How does Append work on an Empty Array?

1 replies
Last updated: Mar 4, 2021
I assume this is normal behavior, but I found that when trying to use the mutations API to patch (https://www.sanity.io/docs/http-patches#insertion-febxf6Fk ) a new reference into an array, the “append” does not work if the array is empty.
{
  "insert": {
    "after": "some.array[-1]",
    "items": ["a"]
  }
}
Prepend works on an empty array, though.

{
  "insert": {
    "before": "some.array[0]",
    "items": ["a"]
  }
}

Feb 27, 2021, 10:26 AM
Turns out I was wrong about this. The root cause was that both append and prepend failed if the array did not already exist on that document. So I have to add a separate patch command first to create/initialize it.
setIfMissing": {  
       "some.array": []    
      },

Mar 4, 2021, 9:27 AM

Sanity– build remarkable experiences at scale

Sanity is a modern headless CMS that treats content as data to power your digital business. Free to get started, and pay-as-you-go on all plans.

Was this answer helpful?