Karlo
Karlo

Reputation: 282

Sanity.io reusable schema field types

I'm new to Sanity.io. I'm just wondering if there is a way that I can optimize my codes and reuse the fields in different schemas.

Im thinking something like this:

cars.ts:

export default {
    name: 'cars',
    title: 'Cars',
    type: 'document',
    fields: [vehicleName]
}

trucks.ts:

export default {
    name: 'trucks',
    title: 'Trucks',
    type: 'document',
    fields: [vehicleName]
}

vehicleName.ts:

export const vehicleName = {
    name: 'name',
    title: 'Name',
    type: 'string',
    validation: Rule => Rule.required()
}

Upvotes: 1

Views: 1234

Answers (2)

Arnab_Ghosh
Arnab_Ghosh

Reputation: 329

Yes, certainly you can !

You can create a vehicleType.ts file like this :

import {defineType} from 'sanity'

export const vehicleType = defineType({
  name: 'vehicle',
  type: 'object',
  fields: [
    {name: 'attr', type: 'string', title: 'Attribute'},
    {name: 'value', type: 'string', title: 'value'},
  ],
})

Make sure to put the types in index.ts file in schemaTypes dir:

export const schemaTypes = [carType, vehicleType]

Then in the carType.ts file, you can use it like:

import {defineField, defineType} from 'sanity'

export const carType = defineType({
  type: 'document',
  name: 'cars',
  title: 'Cars',
  fields: [
    defineField({
      name: 'cars',
      title: 'cars',
      type: 'array',
      of: [{ type: 'vehicle' }],
    }),
  ]
})

Note: I used an object type instead of string type in the example since I believe that'd be the usecase in real world scenario.

Upvotes: 1

88 Create
88 Create

Reputation: 16

    {
  title: 'Vehicle Names',
  name: 'vehicles',
  type: 'array',
  of: [
    {
      type: 'reference',
      to: [
        {type: 'cars'},
        {type: 'trucks'}
      ]
    }
  ]
}

You can use references to access the cars and trucks in as many different schemas as you want making your code reusable

export default {
    name: 'trucks',
    title: 'Trucks',
    type: 'array',
    fields: [
    {
      title: 'Names',
      name: 'names',
      type: 'reference',
      to: [{type: 'vechicleName'}]
    }
  ]
}

Sanity is bi-directional

Upvotes: 0

Related Questions