Extract the data from a fetch request and export it

Viewed 975

I'm happy to join the StackOverFlow community.

I am new to web development and have billions of questions.

My question will concern a fetch request in javascript.

I'm trying to extract the data (userId) from the response in order to export it but I can't.

I tried to set the userId variable to global but it doesn't work.

Is there anyone who could help him on this issue.

Thank you in advance for your answers.

let userId = "";

let loggedUserId = () => {
  let storageToken = localStorage.getItem("groupomania");
  let objJson = JSON.parse(storageToken);
  let token = objJson.token;

  let params = token;

  const headers = new Headers();
  headers.append("Authorization", `Bearer ${token}`);

  let url = "http://localhost:3000/api/user/userId/" + params;

  const parametresDeRequete = {
    method: "GET",
    headers: headers,
  };

  fetch(url, parametresDeRequete)
    .then(function(response) {
      if (response.status !== 200) {
        console.log(
          "Looks like there was a problem. Status Code: " + response.status
        );
        return;
      }

      response.json().then(function(data) {
        userId = data.data;

        console.log(
          "%c ⚠️ Utilities Logged User Id ⚠️ ===>>",
          "color:red ;  font-size: 15px",
          userId
        );
      });
    })

    .catch(function(err) {
      console.log("Fetch Error :-S", err);
    });
};

loggedUserId();

1 Answers

You need to return response.json() in your first then. Then you chain another then to that one where you receive your data (if any was sent to you). Be sure that the data you receive is json.

fetch(url, parametresDeRequete)
    .then(function(response) {
      if (response.status !== 200) {
        console.log(
          "Looks like there was a problem. Status Code: " + response.status
        );
        return;
      } else {
        return response.json(); // returns unresolved Promise
      }
     }
     .then(function(data) {  // data refers to the resolved promise. If the response is not json then the previous .json() method will throw an error which you will be able to catch with .catch()
        userId = data.id;

        console.log(
          "%c ⚠️ Utilities Logged User Id ⚠️ ===>>",
          "color:red ;  font-size: 15px",
          userId
        );
      });
    })
    .catch(function(err) {
      console.log("Fetch Error :-S", err);
    });
Related