Unlock seamless workflows and faster delivery with our latest releases - Join the deep dive

Asynchronous List Options Component

By RD Pennell

Populate your list options in a string schema using an external API

schema.js

{
  name: 'catBreed',
  title: 'Cat Breed',
  type: 'string',
  options: {
    list: [],
    url: 'https://catfact.ninja/breeds',
    formatResponse: (json) =>
      json.data.map(({breed}) => ({
        title: breed,
        value: breed.toLowerCase().split(' ').join('-'),
      })),
  },
  components: {
    input: AsyncSelect,
  },
},

AsyncSelect.js

import {useState, useEffect} from 'react'

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

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

    getCats()
  }, [url, formatResponse])

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

export default AsyncSelect

The Studio will break if you try to use an API call to populate your list options. Instead, you can use a custom input component and the renderDefault method to handle this in just a few lines of code.

Contributor

Other schemas by author