How to fetch data from an external API for a custom component in Sanity.io.

2 replies
Last updated: Sep 8, 2023
I have a requirement where the string options list should come from sanity. Like list of all the pages created and show it in options list below.
{
      name: 'goToPage',
      title: 'Go to page',
      description: 'This will be the page you would like the users to go to.',
      type: 'string',
      options: { list: PAGE_TYPES }, //This is where I want the data to come from sanity rather than pre-defined.
    },
Sep 7, 2023, 5:26 PM
You would need to create a custom component to handle this. Here’s one that fetches an external API that you can adapt:
{
	title: 'Async List',
  name: 'asyncList',
  type: 'string',
  options: {
    list: [], // <-- list must be an empty array initially to avoid errors
    url: '', // <-- the url you want to fetch
		formatResponse: (data) => {} // <-- a function to transform the data to match the schema requirements: { title, value }
  }, 
	components: {
		input: AsyncListInput
	}
}

//input component
import {useState, useEffect} from 'react'

export const AsyncListInput = (props) => {
	const [listItems, setListItems] = useState([])
  const {schemaType, renderDefault} = props
  const {options} = schemaType
  const {url, formatResponse} = options

  useEffect(() => {
    const getListItems = () =>
      fetch(url)
        .then((res) => res.json())
        .then(formatResponse)
        .then(setListItems)

    getListItems()
  }, [url, formatResponse])

  return renderDefault({
    ...props,
    schemaType: {...schemaType, options: {...options, list: listItems}},
  })
}

//general usage
{
	name: 'catBreed',
	title: 'Cat Breed',
	type: 'asyncList',
	options: {
		url: '<https://catfact.ninja/breeds>', // <-- the url you want to fetch
    formatResponse: (json) => // <-- a function to transform the data to match the schema requirements
      json.data.map(({breed}) => ({
        title: breed,
        value: breed.toLowerCase().split(' ').join('-'),
      })),
		}
}
Sep 7, 2023, 6:33 PM
Thank you for your help.I will try this and get back if any help needed.
Sep 8, 2023, 6:35 AM

Sanity– build remarkable experiences at scale

Sanity is a modern headless CMS that treats content as data to power your digital business. Free to get started, and pay-as-you-go on all plans.

Was this answer helpful?