0

I'm just getting started with javascript so please bear with me. I'm trying to fetch a value from an API but I'm struggling with it.

This "works" as in it prints the name I'm trying to get.

let nameURL = "/login/userInfo/name?email=" + email;

 fetch(nameURL, { method: "GET" })
  .then((res) => res.json())
  .then((json) => {
    console.log(json[0])
    
  });

This doesn't work, returns an undefined value:

let nameURL = "/login/userInfo/name?email=" + email;



function getName() {
    fetch(nameURL, { method: "GET" })
      .then((res) => res.json())
      .then((json) => {
        return json[0]
        
      });
  }
  
  console.log(getName())

What I want to do is use that function to bring out json[0], as I need it to use that information.

EDIT: since I'm using React, I ended up using the fetch call inside a component and then using hooks to set values.

Impasse
  • 85
  • 9
  • 1
    your function doesn't return anything. you have to assign the return value from you fetch to a variable and return that variable – Aalexander Jan 11 '21 at 14:50
  • 1
    You have to wait on the the result to return too. fetch, and other things are asynchronous so extra steps have to be taken. – r3wt Jan 11 '21 at 14:52
  • 1
    Does this answer your question? [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – Liam Jan 11 '21 at 15:02
  • @Liam as I said I'm really a beginner with js (and even more a beginner with async stuff), so I really can't find an answer by reading that thread. I can't seem to find what's wrong with my code by reading that :/ – Impasse Jan 11 '21 at 17:38

1 Answers1

3
let nameURL = "/login/userInfo/name?email=" + email;

// this is your function: it works fine, except that you need to
// `return fetch`, and you don't need to specify `GET` because
// that's the default
function getName() {
  return fetch(nameURL)
    .then((res) => res.json())
    .then((json) => json[0]);
}

// You need to `.then` it to get the result, 
getName().then((name) => {
  // do other work with `name`
})

As @Alex said you can also do this with the async/await syntax:

async function getName() {
  const res = await fetch(nameURL)
  const json = await res.json()
  return json[0]
}

// somewhere else
getName().then((name) => {});
// or
(async () => {
  const name = await getName()
})();
Evert
  • 93,428
  • 18
  • 118
  • 189
Zac Anger
  • 6,983
  • 2
  • 15
  • 42