Knut Melvær
Knut is a principal developer marketing manager at Sanity.io
Use data for the current logged in user as initial values in a new document
// 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
}
*/
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.
Knut is a principal developer marketing manager at Sanity.io
Automatically track when content was first published with a timestamp that sets once and never overwrites, providing reliable publication history for analytics and editorial workflows.
Go to First Published Timestamp FunctionAI-powered automatic tagging for Sanity blog posts that analyzes content to generate 3 relevant tags, maintaining consistency by reusing existing tags from your content library.
Go to Auto-Tag FunctionThis can be used for blogs or articles where you want to possibly display next and previous article buttons
Go to Get current post, previous post, and next postHow to automatically generate linked headings with a custom serializer
Go to Anchored Headings for Portable Text