page-application in javascript without framework. I'm stuck with this problem of promise that returns undefined. I just get undefined on the html page.
I had a lot of trouble passing the variable between the two functions getJsonData and showPhotographers.
- To do this I used the variable definition inside the block
if(1 ==1)and I definedjson = getJsonData(); Like that the variable is well defined. If you have the solution to this problem thank you in advance here is my code:
let json;
// get Json Data
const getJsonData = () => {
return fetch('../../db/FishEyeData.json').then((response) => {
return response
.json()
.then((data) => {
json = data;
return data;
})
.catch((err) => {
console.log(err);
});
});
};
// get Photographers
const getPhotographers = () => {
return new Promise((resolve, reject) => {
getJsonData().then((data) => {
console.log(data);
return resolve(data.photographers);
});
});
};
// share scope json
if(1 == 1) {
json = getJsonData();
}
const showPhotographers = () => {
// get the values
if (json !== undefined) {
// load the images
// function html Photographers section
console.log(json);
const html = JSON.stringify(json)
.photographers?.map((user) => {
const str = user.name;
const dash = str.replace(" ", "-");
console.log(dash);
return `
<div class="user ">
<a href="#${dash}">
<div class="circle thumb">
<div class="crop">
<img src="img/${user.portrait}" alt="" />
</div>
<h2 class="name">${user.name}</h2>
</div>
</a>
<p class="city">${user.city}</p>
<p class="tagline">${user.tagline}</p>
<p class="price">${user.price} €/jour</p>
<ul class="tags">
${user.tags
.map((tag) =>
`
<li>
<a href="#" class="${tag}">#${tag}</a>
</li>
`.trim()
)
.join("")}
</ul>
</div>
`;
})
.join("");
document.querySelector("#app").insertAdjacentHTML("afterbegin", html);
}
}
export { json, getJsonData, getPhotographers, showPhotographers };
The file FishEyeData.json looks like this
{
"photographers":[
{
"name":"Mimi Keel",
"id":243,
"city":"London",
"country":"UK",
"tags":[
"portrait",
"events",
"travel",
"animals"
],
"tagline":"Voir le beau dans le quotidien",
"price":400,
"portrait":"MimiKeel.jpg"
}
]
You're overcomplicating things.
fetchreturns a promise, so you can use the result of that ingetPhotographers. In this example I return some data from a fakeAPI call after two seconds, and log the name of the photographer.