Home > OS >  Unable to use the response gathered by Fetch API and use it in my code later
Unable to use the response gathered by Fetch API and use it in my code later

Time:07-15

I'm trying to build a HTML, CSS, JS website and want to incorporate an API and use the response further in my website.

I've managed to make this API part work but I'm stuck with the final part.

  • What I've Achieved

    1. Executing a JS function using FETCH that makes a POST Call with Auth Headers
    2. Getting the response to show up inside my Chrome Developer Console.
  • What I'm trying to achieve

    1. Use the Response (Web URL) that is being received by the POST API Call inside my website as a variable. So when the user hits a button this response (URL) opens up in a new tab.

In simple terms, I want the make use of the web url that shows up in the Chrome Console.

Here is the code I'm using

  function initiateIDV(){

  var myHeaders = new Headers();
  myHeaders.append("Content-Type", "application/json");
  myHeaders.append("Authorization", "Basic xxxxxxxxxxxxx");
  
  var raw = JSON.stringify({
    "customerInternalReference": "Will's App",
    },
    "userReference": "test-app",
    "tokenLifetime": "10m"
  });
  
  var requestOptions = {
    method: 'POST',
    headers: myHeaders,
    body: raw,
    redirect: 'follow'
  };

  
  fetch("https://[hidden]/api/v1/accounts", requestOptions)

    .then(response => response.json())
    .then(result => console.log(result.web.href))
    .catch(error => console.log('error', error));   
   
}

CodePudding user response:

Since the fetch will be processed after the button is displayed this is what I would do. Hide the button by default. Then in your success call back, run a function that shows the button and adds the URL to the href.

Also if you want it to load in a new tab, use a link not a button.

So in your example, change

.then(result => console.log(result.web.href))

to

.then(result => showButton(result.web.href))

and add the class goButton to the link that you want them to click on (or whatever you call it, just make sure you change the references in my example.

In my below example, the link is hidden by default in CSS.

Then in my callback function it sets the href to the passed url and adds a class to the button that shows it.

let goButton = document.querySelector(".goButton");

function showButton(url){
  goButton.setAttribute("href",url);
  goButton.classList.add("active");
}

showButton("https://google.com")
.goButton{display:none;}
.goButton.active{display:block;}
<a target="_blank"  href="">CLICK HERE</a>

CodePudding user response:

I think there are 2 things to check first before make sure the value show in the Console.

  1. Network request. Check in the Network panel to see if the network request call successful? If it's not fix the url or the API. Learn inspect network request
  2. Log the result. Log the result object first to see if it contains .web.href. If it's not, fix the API.

I create a working example from your code. Run it and you will see result. I changed the API url to a demo url

function initiateIDV(){

  var myHeaders = new Headers();
  myHeaders.append("Content-Type", "application/json");
  myHeaders.append("Authorization", "Basic xxxxxxxxxxxxx");
  
  // changed body content
  var raw = JSON.stringify({
    title: 'foo',
    body: 'bar',
    userId: 1,
  })
  
  var requestOptions = {
    method: 'POST',
    headers: myHeaders,
    body: raw,
    redirect: 'follow'
  };

  // changed url
  fetch("https://jsonplaceholder.typicode.com/posts", requestOptions)
    .then(response => response.json())
    .then(result => console.log(result))
    .catch(error => console.log('error', error));   
}

initiateIDV();

CodePudding user response:

Let me paraphrase your question. You want to:

  1. make a POST request to an API
  2. handle the API response in your JavaScript code
  3. open a new tab in the user's browser, at the URL contained in the API response

And you are stuck at step 3.

What you are trying to achieve at step 3 is an effect (aka a side effect) on the user's browser.

Also, a minor remark about the terminology you used:

So when the user hits a button this response (URL) opens up in a new tab.

In your example the response is not a URL. You are calling response.json(), so the API response is JSON.

You are already performing a side effect at step 3: console.log(). A lot of stuff is a side effect. Basically everything that changes some kind of state. Printing something in the browser's console, showing an alert dialog, adding/removing CSS classes, adding/removing/altering DOM elements, are all side effects.

The side effect you want to achieve here is to open a new tab in the user's browser. In JS you can do it using this code:

window.open("https://stackoverflow.com/", '_blank').focus()

The state in your scenario is the fact that the browser currently has N tabs open, and after window.open() will have N 1 tabs open. And not only that. Opening a tab in Chrome might spawn a new operating system process (before the relationship was 1 tab => 1 process, but nowadays I don't think so, see here).

  • Related