Initial value template with current user

By Knut Melvær

Use data for the current logged in user as initial values in a new document

initialValueTemplates.js

// initialValueTemplates.js

import T from '@sanity/base/initial-value-template-builder'
import userStore from 'part:@sanity/base/user'

export default {
  ...T.defaults,
  T.template({
    id: 'newsStory',
    title: 'News story',
    schemaType: 'newsStory',
    value: async () => {
      const {name, id} = await userStore.getUser('me')
      return {
        author: {
          name,
          id,
          _type: 'author'
        },
      }
    }
  })
}

/*
Shape of the user object from userStore.getUser('me'):
{
  "id": "pCuO6i54C",
  "projectId": "3do82whm",
  "displayName": "Your name",
  "familyName": "Your family name",
  "givenName": "Your given name",
  "middleName": "Your middle name",
  "imageUrl": "<your-avatar-image>",
  "createdAt": "2018-04-02T14:21:46.688Z",
  "updatedAt": "2020-12-30T08:21:25.286Z",
  "isCurrentUser": true
}
*/

author.js

export default {
  name: 'author',
  type: 'object',
  title: 'Author',
  fields: [
    {
      name: 'name',
      type: 'string',
      title: 'Full name'
    },
    {
      name: 'id',
      type: 'string',
      title: 'User ID',
      readOnly: true,
      description: `This author's user ID. Used for workflow scripts and similar.`
    }
  ]
}

This example shows how to use the userStore to fetch the logged-in user, and use the data from the user object to populate an author field using the Initial Value Templates API.

Contributor

Other schemas by author

Breaks for Portable Text

How to add different types of “breaks” for Portable Text that can be translated to horizontal rules, “read more”, sections, chapters, and so on.

Knut Melvær
Go to Breaks for Portable Text