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 />
);
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}
/>
)
}
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 />
);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With