How do to get returned value from a function and use it inside another function?

Hi

I’m trying to get the value from the first function and use it inside my second function.

When console.log the first function I get the value I want but don’t know why it doesn’t work on the second function.

I get this error: Uncaught (in promise) TypeError: Cannot read property ‘name’ of undefined

My code:

const countryName = document.querySelector(".searchResult")
  .addEventListener("click", (e) => {
    let target = e.target.lastChild.innerHTML;
    console.log(target);

    return target;
  });

function infoTemplate() {
  getData()
  .then((data) => {
    console.log(data);
    const result = data.find(({ name }) => name === countryName);
    let focusedName = document.querySelector(".focusedName");
    focusedName.innerHTML = result.name;
  });
}

infoTemplate();

Hi @KarimZ, that probably means that you didn’t find() anything that matches the country name, in which case undefined is returned. So you’d have to verify that there is a match first:

if (result) {
  focusedName.innerHTML = result.name
}

Or maybe using a ternary expression:

focusedName.innerHTML = result ? result.name : 'No match found'

BTW why are you using const for the result, but let for the element? Personally I’d prefer const over let whenever possible, but there are good reasons for either convention. At any rate, I’d keep it consistent.

1 Like

The first function returns a country name as it reads what’s inside a H1 element, I don’t get undefined in return. I want to use the string inside the h1inside the infoTemplate function.

Because if I change the countryName inside the second function to a string of a country, the function works fine.

Ah yes, there’s another problem. You’re assigning the return value of addEventListener() to countryName, which is also undefined – what you are returning from inside the listener callback doesn’t go anywhere. That function will get called back at some point in the future (namely when the user clicks .searchResult), but infoTemplate() is getting called immediately:

  1. Add event listener
  2. Render info template
  3. User clicks element – where should the return value go?

So you’d have to call infoTemplate() inside the event listener callback, and pass the country name:

function infoTemplate (countryName) {
  getData().then((data) => {
    const result = data.find(({ name }) => name === countryName)
    const focusedName = document.querySelector('.focusedName')

    focusedName.innerHTML = result ? result.name : 'No match found'
  })
}

document
  .querySelector('.searchResult')
  .addEventListener('click', (e) => {
    const target = e.target.lastChild.innerHTML

    infoTemplate(target)
  })
1 Like

Thank you again!
Have learned alot from you, thank you.

2 Likes

No worries. :-)

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.