-
Notifications
You must be signed in to change notification settings - Fork 13
Expand file tree
/
Copy pathindex.tsx
More file actions
60 lines (55 loc) · 2 KB
/
Copy pathindex.tsx
File metadata and controls
60 lines (55 loc) · 2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
import {asyncList} from '@sanity/sanity-plugin-async-list'
import {definePlugin, defineType} from 'sanity'
const asyncListTest = defineType({
type: 'document',
name: 'asyncListTest',
title: 'Async List',
fields: [
{type: 'string', name: 'title', title: 'Title'},
{type: 'pokemon', name: 'pokemon', title: 'Pokemon (seed loader)'},
{type: 'disneyCharacter', name: 'disneyCharacter', title: 'Disney Character (search loader)'},
],
})
export const asyncListExample = definePlugin(() => ({
name: 'async-list-example',
schema: {types: [asyncListTest]},
plugins: [
// Seed loader: fetches the options once when the field is rendered
asyncList({
schemaType: 'pokemon',
loader: async () => {
const response = await fetch('https://pokeapi.co/api/v2/pokemon?limit=151&offset=0')
const result: {results: {name: string}[]} = await response.json()
return result.results.map((item) => ({value: item.name}))
},
autocompleteProps: {
placeholder: 'Search Pokemon',
},
}),
// Search loader: re-runs the loader with the user's query as they type
asyncList({
schemaType: 'disneyCharacter',
loaderType: 'search',
loader: async ({query}) => {
const url = query
? `https://api.disneyapi.dev/character?name=${encodeURIComponent(query)}`
: 'https://api.disneyapi.dev/character'
const response = await fetch(url)
const result: {data: {name: string}[] | {name: string} | null} = await response.json()
const characters = Array.isArray(result.data)
? result.data
: result.data
? [result.data]
: []
// The API can return multiple characters with the same name, but
// option values must be unique
const names = new Set<string>()
return characters.flatMap((item) => {
if (names.has(item.name)) return []
names.add(item.name)
return [{value: item.name}]
})
},
}),
],
}))