Knut Melvær
Knut is a principal developer marketing manager at Sanity.io
Knut is located at Oslo, Norway
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
This 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 TextMigration script to convert plain text to block content across your content lake
Go to Migrate plain text field to Portable TextSimple content type for a question and answer pattern
Go to Frequently asked questions