Retrieve the information from a fetch call and save it for later use

Greetings to the wonderful StackOverFlow community.

As a beginner in web development, I have countless questions swirling in my mind.

The focal point of my query is regarding a fetch request in JavaScript.

I am struggling to extract the data (userId) from the response for exporting purposes.

Despite attempting to set the userId variable as global, I am facing issues.

If there is anyone out there who could lend a helping hand on this matter, it would be greatly appreciated.

Many thanks in advance for your valuable insights!

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();

Answer №1

Make sure to include response.json() in the first then block. Afterwards, chain another then block to handle the data you receive, ensuring that it is in JSON format.

fetch(url, requestParameters)
    .then(function(response) {
      if (response.status !== 200) {
        console.log(
          "There seems to be an issue. Status Code: " + response.status
        );
        return;
      } else {
        return response.json(); // returns unresolved Promise
      }
     })
     .then(function(data) {  
        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);
    });

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

unable to clear form fields after ajax submission issue persisting

After submitting via ajax, I am having trouble clearing form fields. Any help in checking my code and providing suggestions would be greatly appreciated. Here is the code snippet: jQuery(document).on('click', '.um-message-send:not(.disabled ...

Is it possible to detect inline elements that have been wrapped?

I am facing a challenge with displaying an indefinite amount of in-line elements. Depending on the width of the browser, some elements may shift to a new line. I am curious to know if it is possible to identify and isolate these rows of elements, or if the ...

A specialized identifier for nested objects in a React component

I am currently working with a JSON data structure that looks like this: [ [ { city: x patients: x id: 1 }, { city: y patients: y id: 2 } ], [ { city: x patients: x id: 1 }, { city: y patients: y id: 2 } ...

Create multiple new routes leading to a central page on your Nuxt application

I'm having trouble with the folder and route structure in Nuxt for a project: My goal is to have all of them display pages/data/index.vue: www.example.com/data www.example.com/data/region www.example.com/data/region/industry And then be able to acc ...

Transform an array of arrays object with multiple depths into an array of objects

Having some difficulty with the conversion of an array of arrays-like object into an array of objects. The reduce method is being used, and it successfully converts the array data to an object for the first set of arrays. However, on the second iteration, ...

What will be the quickest and most reliable trigger - matchMedia, window.resize, orientationchange, or perhaps both combined?

I am trying to trigger a function when a user rotates their device and I'm seeking advice on which event would be most effective for this purpose. In your experience, which event do you recommend that will call the function quickly and consistently? I ...

What is the best way to determine the total number of rows that have been generated by the Asp:Repeater?

I'm looking for a way to retrieve the total number of rows generated by the repeater control using either Javascript or JQuery. Can anyone help me with this? ...

What is the significance of utilizing app.set() and app.get() in applications?

Is there a way to simplify this code: app.set('port', (process.env.PORT || 3000)); const server = app.listen(app.get('port'), () => { console.log('Server|Port: ', app.get('port')); }); Here is an alternative ...

The solution for resolving vue updates using checkboxes

I am currently working on creating a tree view with checkboxes where the parent node's state is always based on its children, including indeterminate values, and v-model it into an array. Here's what I have managed to do so far. The issue arises ...

Angular factory transforming service

I am looking to transform the 'i18n' function into a factory in order to return a value instead of just setting it. Any suggestions or tips would be greatly appreciated! services.factory('i18nFactory', function() { var language = ...

Tips for sending an array of input field values through an Ajax request

In my current web form, there is a dynamic option that adds rows with the same attributes. These rows need to be submitted through an Ajax call to my PHP for insertion into the database. Access: <tr> <td><input type"text" name="access[nam ...

Locate the index of each distinct element within the array

Let's define an array called 'arr' with some elements: [7, 9, 30, 40, 50, 8, 1, 2, 3, 40, 90,2, 88,1] We also have another output array defined as: [0, 1, 2, 3, 4, 5, 6, 7, 8 ,10, 12] I stored this code snippet on a javascript ...

Escaping back slashes in Node.js

I am currently encountering an issue with escaping backslashes. Below is the code snippet that I have attempted. The problem lies in how to assign a variable containing an escaped slash to another variable. var s = 'domain\\username'; ...

Enhancing the shadow effects on ThreeJS using buffergeometry

I'm currently working on a project where I have loaded a .gltf model in ThreeJS with a keyframe animation that alters the shape of the object (it's a point level animation). Everything seems to be functioning correctly, except for the fact that t ...

Creating a unique kendo ui widget from scratch

Is there a way to create a custom widget that functions similarly to the example shown in this sample: http://jsfiddle.net/anilca/u2HF7/ I found some helpful information here, but I'm struggling with defining dropdownlist templates and linking them ...

What is the best way to have an image trail another in JavaScript coding for my game?

Hey, can someone help me create a zombie game where a zombie image moves towards a player image (zs.png) at a specific speed and decreases the player's health upon contact? This game is designed for the 3ds browser, so it must be coded in JavaScript ...

Dynamic Node.js server constantly updating

My goal is to create a dynamic Node.js Express server that updates live, possibly by creating a specific route like /update to load a new configuration file. My concern is that the server could be in any state when the update occurs. It's possible tha ...

Finding a nested div within another div using text that is not tagged with XPath

I need help creating an XPath to select a div with the class "membername" using the parameter "Laura". <div class="label"> <div class="membername"></div> David </div> <div class="label"> < ...

What is the best way to apply a hover rule to a CSS class in order to change the color of a specific row when hovering in

I have managed to successfully apply a classname and add color to a specific row in my react-table. However, I am facing difficulty in adding a hover rule to this className to change the color when I hover over the row. Can someone guide me on how to apply ...

eliminating attributes from a JavaScript object

Seeking a method to strip object properties before sending them to the front-end. Why does this code work as intended: var obj = { name: 'cris', age: 22, } console.log(obj) //displays name and age delete obj.name console.log(obj) //dis ...