I'm implementing an autocomplete input with react-select. To load autocomplete options, I need to fetch an api.
I need to do this task on two endpoints, one which is just the url (this one I got) but this one is different: I need to send a json body with the following contents :
{"searcher" : "VALUE"}
where the value would be the terms that the user would look for, that is, a variable that I attribute to the input.
But I can't do a search and it's not returning anything when I put this code, which is basically the logic I used on the endpoint that only needs the URL. where am I going wrong?
I have the collection of the api in postman and I tested it by sending the json body and it works, but in the code, no
const INITIAL_DATA = {
value: 0,
label: 'Selecione o Procedimento',
};
const [selectData, setselectData] = useState(INITIAL_DATA);
const mapResponseToValuesAndLabels = (data) => ({
value: data.id,
label: data.terminologia,
});
async function callApi(value) {
/* var data = JSON.stringify({
"buscador": "CAP"
}); */
const api = axios.create({
baseURL: `http://devsite.redetelemedicabr.com.br:3333/medsigtap/byTerminologia`,
headers: {
'Content-Type': 'application/json',
'Accept' : '*/*'
},
data :JSON.stringify({
"buscador": "CAP"
})
})
api.get('/').then(res => {
console.log(res.data,'fefe')
})
}
return (
<div>
<p></p>
<AsyncSelect
cacheOptions
loadOptions={callApi}
onChange={(data) => {
setselectData(data);
}}
value={selectData}
defaultOptions
/>
in this code, I need to get the response from API and map it to have a label and value so it can show it on the autocomplete options.
I'm getting on response log only an empty array [] but in postman it works , i received what I'm looking for (the CAP objs )
the problem is you are not sending the data correctly
send the jsonData like this:
const rawResponse = await fetch(url, {
method: 'POST',
body: JSON.stringify(jsonData),
});
const response = rawResponse.json().map(mapResponseToValuesAndLabels);