如何将 useQuery 与 React Async Select 结合使用

问题描述 投票:0回答:1

https://react-select.com/async:React 异步选择库

https://redux-toolkit.js.org/rtk-query/overview:RTK 查询

如何将 useQuery 提供的方法与 React Async 库结合使用。

我无法利用它,因为重新获取不接受回调。

我能够使用正常的函数调用来实现它。(例如下面给出的)

import React from 'react';

import AsyncSelect from 'react-select/async';
import searchSomethigFromAPI from '@something';

const searchFromAPI = (value,callback) => {
   searchSomethigFromAPI()
   .then(res => {
       const result = res.data.filter(e => e.name);
       callback(result);
   })
   .catch(err=>{console.log(err)}
}

export default () => (
  <AsyncSelect cacheOptions loadOptions={searchFromAPI} defaultOptions />
);
javascript reactjs react-select rtk-query
1个回答
-1
投票

您可以将 useLazyQueryloadOptions 一起使用。

以下是其工作原理的部分片段:

export default function SearchProducts() {
  const [ getProducts ] = useLazyGetProductsQuery();
  
  const getProductOptions = async (query) => {
    const products = await getProducts({}).unwrap();
    
    return products.map((product) => ({
      value: product.id,
      label: product.name,
    }));
  };

  return (
    <AsyncSelect
      // other options...
      loadOptions={getProductOptions}
    />
  )
}
© www.soinside.com 2019 - 2024. All rights reserved.