1

I am trying to understand JavaScript, specifically fetch. I have the following code but it is not making sense to me because console.log(responseObject) prints data but console.log(res) prints undefined.

How is that possible? Why is responseObject not getting passed into res?

I do not want to mess around with async/await keyword as I find .then to be a lot cleaner.

  export const retrieveBasicUserData = (usernameFieldValue, setStateFunction) => {
  const responseObject = {
    data: null,
    error: null,
  };

  fetch(`https://api.github.com/users/test`)
    .then((response) => {
      response.json().then((data) => {
        responseObject.data = data;
        console.log(responseObject);
        return responseObject;
      });
    })
    .then((res) => console.log(res));
};
vishalkohli
  • 87
  • 1
  • 2
  • 9
  • Your first `then` callback doesn't return anything so the chained `then` callback will receive nothing. Try adding `return` in front of `response.json()...` – Phil May 22 '20 at 00:17
  • 1
    Can't see why this might be classed as a duplicate of https://stackoverflow.com/q/14220321/3478010. – Roamer-1888 May 22 '20 at 08:34
  • @Phil Isn't return of a arrow function implicit. I mean it works here : fetch (URL).then(response => response.json()) .then (json=> console.log(json)) – vishalkohli May 22 '20 at 17:06
  • 2
    Return of an arrow function is implicit only if you omit curly braces {}. – Roamer-1888 May 22 '20 at 17:09
  • 1
    @Roamer you might be right about the duplicate. One focusing on promise chaining would be more appropriate. Like this one https://stackoverflow.com/q/22539815/283366 – Phil May 22 '20 at 23:53

0 Answers0