Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use useQuery with React Async Select

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 />
);
like image 852
k1941996 Avatar asked Oct 17 '25 00:10

k1941996


2 Answers

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}
    />
  )
}
like image 117
Neville Omangi Avatar answered Oct 19 '25 14:10

Neville Omangi


If you really want to use it that way,

first create a new custom hook for using useQuery

const useCustomSearch = (searchApi) => {
  const { data, refetch } = useQuery(searchApi, {
    skip: true, // you should skip the initial query
  });

  const loadOptions = (inputValue, callback) => {
    refetch(inputValue)
      .unwrap()
      .then((newData) => {
        // Do whatever to shape the data
        let options=newData.filter()
        callback(options);
      })
      .catch(error => console.error(error));
  };

  return loadOptions;
};

Then you can use it with AsynSelect

 const loadOptions = useCustomSearch(searchSomethigFromAPI);

  return (
    <AsyncSelect cacheOptions loadOptions={loadOptions} defaultOptions />
  );

like image 34
mcnk Avatar answered Oct 19 '25 12:10

mcnk