0

I am trying to assign a variable after fetch in reactjs, it is not being assigned after the fetch for the code below:

    var apiBase = '';
    fetch('/AppSettings/GetSettings')
      .then(response => { return response.text() })
      .then(data => {apiBase = data; console.log("Within Call:" + apiBase); })
      .catch(err => {console.log("Error :" + err) });
Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
Mostafa
  • 169
  • 1
  • 3
  • 12
  • `fetch` / promises are **asynchronous** . Anything that needs access to `data` should be contained or called from the same place where you do `console.log("Within Call:" + apiBase);`. – Felix Kling Jun 14 '18 at 00:00
  • 1
    If you could do what you wanted to do, then there would be no reason to have promises / callbacks in the first place and you would be able to just do `var apiBase = fetch('/AppSettings/GetSettings').text()`. But since the process of fetching data from the network is *asynchronous* we have to provide callbacks to notify us when the data is available. – Felix Kling Jun 14 '18 at 00:03
  • @Felix I'm now getting the value by using async and await, but returned value is not getting passed to the next fetch where I need to return a list of values.; below is my code snippet: return await fetch(apiBase + '/StandardCostItem') .then(response => response.json() as Promise) .then(standardCostItems => Array.from(standardCostItems, c => new StandardCostItem(c))); the variable apiBase is not getting the assigned value from the other fetch, appreciate your response – Mostafa Jun 14 '18 at 00:13
  • `async`/`await` is just syntactic sugar for working with promises. It doesn't solve the underlying problem of the code being asynchronous but you wanting it to be synchronous. An `async` function always returns a promise. – Felix Kling Jun 14 '18 at 00:19

0 Answers0