Created
January 16, 2021 15:07
-
-
Save tavareshenrique/5b95ff7c1f0fdcb6a19ee648c9d2e8df to your computer and use it in GitHub Desktop.
AsyncSelect Component
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React, { useCallback } from "react"; | |
import debounce from "lodash/debounce"; | |
import AsyncSelect from "react-select/async"; | |
import axios from "axios"; | |
const App = (props) => { | |
const options = [ | |
{ label: "Option 1", value: 1 }, | |
{ label: "Option 2", value: 2 }, | |
{ label: "Option 3", value: 3 } | |
]; | |
const getAsyncOptions = (inputText) => { | |
const candidate = inputText.toLowerCase(); | |
const byLabel = ({ label }) => label.toLowerCase().includes(candidate); | |
// remove this line and uncomment below to try with your impementation | |
return new Promise((resolve) => | |
setTimeout(resolve, 1, options.filter(byLabel)) | |
); | |
/* | |
return axios | |
.get(`/v1/user?username=${inputText}`) | |
.then((response) => { | |
return response.data.map((user) => ({ | |
value: user.id, | |
label: user.username, | |
})); | |
}) | |
.catch((error) => { | |
alert(JSON.stringify(error)); | |
}); | |
*/ | |
}; | |
const loadOptions = useCallback( | |
debounce((inputText, callback) => { | |
getAsyncOptions(inputText).then((options) => callback(options)); | |
}, 1000), | |
[] | |
); | |
return ( | |
<AsyncSelect | |
// cacheOptions | |
loadOptions={loadOptions} | |
defaultValue={[]} | |
isMulti | |
isClearable | |
defaultOptions={[]} | |
/> | |
); | |
}; | |
export default App; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment