如何使用 Recoil 将数据动态分配给 atomFamily?

How to dynamically assign data to an atomFamily with Recoil?

如果我获取动态数据,如何在不违反钩子规则的情况下将其放入atomFamily? useSetRecoilState 要求我传入 atomFamily(someIndex),但是对于动态数据,我没有 someIndex 直到 获取数据之后。所以看起来我应该 const setterFactory = someKey => useSetRecoilState(useAtomFamily(someKey)) 但这违反了钩子规则。

示例:

假设我有一个 API 响应伴随类型(和 recoil atomFamily)

type Foo = unknown & { index: string }
type Response = {
  foos: Foo[]
}
const myAtomFamily = useAtomFamily<Foo, string>({
  key: 'foo',
  default: null,
})
declare const fetchFromApi = () => Promise<Foo[]>

所以如果我有自定义挂钩,

const myHook = () => {
  const fooSetter = useSetRecoilState(myAtomFamily(???))

  useEffect(() => {
    fetchFromApi().then(foos => {
      foos.forEach(foo => fooSetter(???)(???))
    })
  }, [])
}

您可以为此使用 useRecoilCallback 挂钩,它基本上是一个工厂挂钩,可让您访问 set 函数:

const useMyHook = () => {
  const fetchAndSet = useRecoilCallback(({set}) => async () => {
    const foos = await fetchFromApi();

    foos.forEach(foo => set(myAtomFamily(foo.id), foo))
  }, [])

  useEffect(fetchAndSet, [])
}