I'm very new to ReactJS
, I'm trying to create a component with a list of values(should be fetched from an API) and should allow the search.
https://codesandbox.io/s/v1v1xp1xn3
Above example is working fine, but it uses local data. How to integrate with remote data. Upon every key press, it should hit API and fetch new data.
What you're looking for is the React-Select AsyncSelect
, as @Laura stated. The documentation is a little confusing. Here's the base example in the docs:
import React, { Component } from 'react';
import AsyncSelect from 'react-select/lib/Async';
import { colourOptions } from '../data';
const filterColors = (inputValue: string) => {
return colourOptions.filter(i =>
i.label.toLowerCase().includes(inputValue.toLowerCase())
);
};
const promiseOptions = inputValue =>
new Promise(resolve => {
setTimeout(() => {
resolve(filterColors(inputValue));
}, 1000);
});
export default class WithPromises extends Component {
render() {
return (
<AsyncSelect cacheOptions defaultOptions loadOptions={promiseOptions} />
);
}
}
You'll see here that the loadOptions
took a promiseOptions
method that returned a Promise that eventually resolved to a list of options. If you replace the internals of that method with a fetch()
(which returns a Promise), then when that request resolved to the list of options, those options would then be applied to the AsyncSelect
.
const promiseOptions = inputValue => {
const url = `my/remote/source${inputValue ? '?searchParam=' + inputValue : ''}`;
return fetch(url)
.then(response => response.json()) // my option list array?
.catch(err => {
console.log('some error', err);
});
};
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