4

https://react-select.com/async: React async Select Library

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

How to utilise the methods provided by useQuery with React Async library.

I was unable to utilise this because refetch does not take in callbacks.

I was able to achieve it using the normal function calls.(eg given below)

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 />
);
kshitiz saini
  • 165
  • 1
  • 9

1 Answers1

0

You can use useLazyQuery with loadOptions.

Here is a partial snippet of how that would work:

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}
    />
  )
}
aphilas
  • 2,066
  • 1
  • 14
  • 9