Created
March 27, 2020 02:19
-
-
Save Dev4ster/9654207653db6b6e4e0fe99474096e0f to your computer and use it in GitHub Desktop.
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, { useState } from 'react'; | |
import AsyncSelect from 'react-select/async'; | |
export default function PageComponent() { | |
const INITIAL_DATA = { | |
value: 0, | |
label: 'Selecione o usuário', | |
}; | |
const [selectData, setselectData] = useState(INITIAL_DATA); | |
const mapResponseToValuesAndLabels = (data) => ({ | |
value: data.id, | |
label: data.name, | |
}); | |
async function callApi(value) { | |
const data = await fetch(`https://jsonplaceholder.typicode.com/users`) | |
.then((response) => response.json()) | |
.then((response) => response.map(mapResponseToValuesAndLabels)) | |
.then((final) => | |
final.filter((i) => i.label.toLowerCase().includes(value.toLowerCase())) | |
); | |
return data; | |
} | |
function handleSubmit() { | |
console.log(selectData); | |
setselectData(INITIAL_DATA); | |
} | |
return ( | |
<div> | |
<p>Exemplo de Async Select com api</p> | |
<AsyncSelect | |
cacheOptions | |
loadOptions={callApi} | |
onChange={(data) => { | |
setselectData(data); | |
}} | |
value={selectData} | |
defaultOptions | |
/> | |
<button type="button" onClick={handleSubmit}> | |
Enviar | |
</button> | |
</div> | |
); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment