🍀

optionをAPIから取得するselectboxを動的に出力する時のtips

2025/02/04に公開

素直にやると、ページロード時に10個のAPIをコールしてしまう。
もっと多い場合もあるので、サーバーの負荷があがる。
その場合は、react-queryを使っていればenabledにフラグを追加する。

この場合は、対象のセレクトボックスにホバーしたらそれに関連するoptionsがfetchされる。

import React, { useState } from 'react'
import { useQuery } from 'react-query'
import { Select } from './Select'
import { fetchSelectFn } from './api'

const SelectWrapper = ({ id }) => {
  const [isHovered, setIsHovered] = useState(false)

  const { data: options = [], isLoading } = useQuery({
    queryKey: ['hoge', id],
    queryFn: async () => fetchSelectFn(id),
    enabled: Number.isInteger(id) && isHovered,
  })

  const handleMouseEnter = () => {
    if (isHovered) return
    setIsHovered(true)
  }

  return (
    <div onMouseEnter={handleMouseEnter}>
      <Select name={`hoge.${id}`} options={options} isLoading={isLoading} />
    </div>
  )
}

const App = () => {
  return (
    <div>
      {[1, 2, 3, 4, 5, 6, 7, 8, 9, 10].map((id) => (
        <SelectWrapper key={id} id={id} />
      ))}
    </div>
  )
}

export default App

Discussion