I'm sure this is an issue with my understanding/implementation. The issue is that I'm trying to return the ID of the created object into an array so that array can later be inserted into another object. Moving the .then() between the function, the call, nothing seems to work. Pushing to the array, assigning the value to the array via index doesn't seem to work. Any insights/guidance into what the root issue is and a path to resolve it is appreciated.
index.js
const contacts = document.getElementsByName('newContact');
const contactName = document.getElementsByName('contactName');
const contactTitle = document.getElementsByName('contactTitle');
const contactPhone = document.getElementsByName('contactPhone');
const contactEmail = document.getElementsByName('contactEmail');
let contactIDArray = new Array();
for (let i = 0; i < contacts.length; i++) {
const name = contactName[i].value;
const title = contactTitle[i].value;
const phone = contactPhone[i].value;
const email = contactEmail[i].value;
var id;
createContact(name, title, phone, email).then(function (res) {
id = res.data.id;
alert(res.data.id);
return id;
});
alert(id);
contact.js
import axios from 'axios';
export const createContact = async (contactName, contactTitle, contactPhone, contactEmail) => {
try {
const res = await axios({
method: 'POST',
url: '/api/v1/contacts',
data: {
contactName,
contactTitle,
contactPhone,
contactEmail,
},
});
return res.data.id;
} catch (err) {
console.log(err);
}
};