I am working on a Javascript, HTML and CSS proyect. What I want is to get the name of a user using its Id. I use fetch to do that but I am getting some problems.
function getUserName(userId) {
let userTemp = window.API_HOST + '/users/' + userId;
return fetch(userTemp, {
headers: { authorization: localStorage.access_token },
})
.then(response => response.json())
.then(response => {
console.log('El nombre es: ' + response.name);
return response.name;
});
}
The problem here is that response.name is a promise object and not the actual name. I tried to use stringify but it did not work. Any suggestions?
EDIT: I need to call that function in a place like this:
function showOffer(newOffer) {
if (newOffer.user_id === JSON.parse(localStorage.current_user)._id) {
const wrapper = document.createElement('div');
wrapper.className = 'wrap';
const prodHolder = document.getElementById('demo').appendChild(wrapper);
const offerBidderId = document.createElement('p');
const offerBidderIdText = document.createTextNode(
'Bidder id: ' + getUserName(newOffer.bidder_id),
);
console.log('New offer bidder id ' + newOffer.bidder_id);
offerBidderId.appendChild(offerBidderIdText);
wrapper.appendChild(offerBidderId);
....
}
Maybe here is the problem?