Extract the data from a fetch request and export it
Asked Answered
T

1

6

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();
Triptolemus answered 31/3, 2021 at 4:39 Comment(1)
Why are you adding a .then() handler inside a .then() handler? Also, what does console.log(response.json()) output?Slag
F
3

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);
    });
Felicitation answered 31/3, 2021 at 5:49 Comment(2)
I don't this will fix the problem. response.json() returns a promise and if a .then() handler is added to a promise that is already resolved, then it will still execute.Slag
Exactly. Returning response.json() returns a Promise, which you will have to catch with your next then block chained to the first one. Try it and you will see :).Felicitation

© 2022 - 2024 — McMap. All rights reserved.