I am trying to get the data using axios, and I built this code:
const getContactList = () => {
var data = {
"list_id": `${myListID}`,
};
const headers = {
'Content-Type': 'application/json',
'Authorization': process.env.apiKey,
};
axios({
method: "POST",
url: "http://localhost:3001/api/get-contacts",
headers: headers,
data: data,
}).then(result => {
const myRes = result.data.list_contacts;
console.log(myRes);
if (myRes != undefined && myRes.length > 0 && myRes != "None") {
return (<div className="border rounded w-full p-2">
<label>Data: </label>
<select className="border rounded" name="mycontactlist" id="mycontactlist">
{myRes.map((item) => {
return (<option name={item.contact_name}>{item.contact_name}</option>)
})}
</select>
</div >)
}
}).
catch(err => {
return (<div>Could not get data.</div>)
});
}
then I try to render it:
return (<div>
{getContactList()}
</div>);
But unfortunately, I don't see anything. I also tried to return the whole axios but it didn't work.
When I log myRes, I see my array -
Array(4)
0: {contact_id: 1, contact_name: "contact", contact_number: "0505975250", contact_list_id: 1, list_id: 1, …}
1: {contact_id: 2, contact_name: "contact", contact_number: "0505975251", contact_list_id: 1, list_id: 1, …}
2: {contact_id: 3, contact_name: "contact", contact_number: "0505975252", contact_list_id: 1, list_id: 1, …}
3: {contact_id: 4, contact_name: "contact", contact_number: "0505972553", contact_list_id: 1, list_id: 1, …}
length: 4
__proto__: Array(0)
What did I do wrong?
I understand that it has something to do with the promise, but I don't get it. Can you help please?