From 8789d89e314b6d517d5ca3afa19d6393cf69b801 Mon Sep 17 00:00:00 2001 From: jbranchaud Date: Fri, 3 Nov 2023 10:59:04 -0500 Subject: [PATCH] Add Add Item To An Array Of References In Sanity as a JavaScript TIL --- README.md | 3 +- ...tem-to-an-array-of-references-in-sanity.md | 28 +++++++++++++++++++ 2 files changed, 30 insertions(+), 1 deletion(-) create mode 100644 javascript/add-item-to-an-array-of-references-in-sanity.md diff --git a/README.md b/README.md index 6d86891..db1e101 100644 --- a/README.md +++ b/README.md @@ -10,7 +10,7 @@ pairing with smart people at Hashrocket. For a steady stream of TILs, [sign up for my newsletter](https://crafty-builder-6996.ck.page/e169c61186). -_1346 TILs and counting..._ +_1347 TILs and counting..._ --- @@ -402,6 +402,7 @@ _1346 TILs and counting..._ ### JavaScript - [Accessing Arguments To A Function](javascript/accessing-arguments-to-a-function.md) +- [Add Item To An Array Of References In Sanity](javascript/add-item-to-an-array-of-references-in-sanity.md) - [Basic Date Formatting Without A Library](javascript/basic-date-formatting-without-a-library.md) - [Character Codes from Keyboard Listeners](javascript/character-codes-from-keyboard-listeners.md) - [Check Classes On A DOM Element](javascript/check-classes-on-a-dom-element.md) diff --git a/javascript/add-item-to-an-array-of-references-in-sanity.md b/javascript/add-item-to-an-array-of-references-in-sanity.md new file mode 100644 index 0000000..a94542b --- /dev/null +++ b/javascript/add-item-to-an-array-of-references-in-sanity.md @@ -0,0 +1,28 @@ +# Add Item To An Array Of References In Sanity + +Let's say we have an existing record in our Sanity dataset. The schema for that +record allows for an array of references to another type of record. As part of +programmatically importing some data, we need to tie some records together by +adding to that array of references. + +We've already set up our [Sanity client](https://www.sanity.io/docs/js-client) +(via the JavaScript SDK). We have an `_id` for the record we want to patch. We +have a `resourceId` for the resource that we want to _reference_ in the array. + +Here is how we perform that `patch`: + +```javascript +await sanityClient + .patch(_id) + .setIfMissing({resources: []}) + .append('resources', [{_type: 'reference', _ref: resourceId}]) + .commit({autoGenerateArrayKeys: true}) +``` + +1. We give it the `_id` of the record we want to `patch`. +2. We set our array of `resources` to an empty array (`[]`) if it hasn't + already been set. +3. We `append` to the `resources` array with an array containing a single item, + a reference to our resource. +4. We `commit` the changes with the directive that Sanity should auto-generate + the `_key` value for any new array items.