0
<!DOCTYPE html>
<head>
    <title>home</title>
</head>

<body>
<h1>login here</h1>
<form id="createuserform" method="post">

    <label>First Name: </label>
    <input id="fname" type="test"></br>

    <label>Last Name: </label>
    <input id="lname" type="text"></br>

    <label>Location: </label>
    <input id="location" type="text"></br>

    <input id="createUser" type="button" value="create user"></br>
    <input id="setter" type="text" value="val">
</form>
<script>
    function submitValue() {
        var r;
        fetch('http://localhost:8080/multimediaApi/api/multimedia/users').then(response => (response.json())).then(data => r = data[0]);
        document.getElementById("setter").value = r;
    }
</script>
<button onclick="submitValue()">Get Data</button>
</body>
</html>

I want to fetch the data from the above API URL and store it in variable r. So, I have used then(data => r= data[0]) to assign value to variable r. and then display it in textfield document.getElementById("setter").value=r. But the value the value in r is coming as undefined.

Henry Ecker
  • 34,399
  • 18
  • 41
  • 57
  • Hello, just to be sure, could you also add a `.catch(e => console.log(e))` onto your call to make sure the fetch request is not erroring out? Also try to log the response you are getting back to make sure it is not undefined, and that it has the right shape for you to access it using `data[0]`. – rexess Nov 07 '21 at 07:28

1 Answers1

2

In the execution of the submitValue function, the value of r will be undefined and initiated a AJAX request which will complete sometime later, and the value gets assigned to

document.getElementById( "setter" ).value = r;

will be undefined which is current value of r.


Later some time the request is completed

So, the following code runs

fetch( 'http://localhost:8080/multimediaApi/api/multimedia/users' )
    .then( response => ( response.json() ) )  // now run
    .then( data => r = data[0] );             // now run

In this you are just assigning the data[0] to r. Rest code already ran before and won't run again. That's how ASYNC JS works.

You should read Understanding JavaScript promise object

You can directly assign the data[0] to the HTML element with id setter as:

function submitValue() {
    fetch( 'http://localhost:8080/multimediaApi/api/multimedia/users' )
        .then( response => ( response.json() ) )
        .then(data => {
            document.getElementById( "setter" ).value = data[0];
        })
}
DecPK
  • 24,537
  • 6
  • 26
  • 42
  • suppose I want to store value of data[0] in a variable and then use it later then for that scenario .then(data => { document.getElementById( "setter" ).value = data[0]; }) this code is not useful. – Amritesh Singh Nov 08 '21 at 08:09
  • For that scenario you have to lift the state to nearest common parent, where you can declare variable and set the value of the variable in `.then` – DecPK Nov 08 '21 at 08:18