1

Me and my friend are trying to make a farm game and you have to make a Bitcoin wallet to start playing. I am using the code below and the request goes perfectly, but it doesn’t show the wallet ID; it only shows it as undefined.

<button onclick="createWallet()">Create Wallet</button>
<script>
async function createWallet() {
  const create = await fetch('https://example.org/?type=create', {
    method: "GET",
    mode: "no-cors",
    headers: {
      "Content-Type": "application/json"
    }
  });
  const createjson = create.json();
  
  localStorage.setItem("walletid", createjson.id);
  alert(`wallet created: ${createjson.id}`);
  // window.location.href = `https://example.org/game?wallet=${createjson.id}`;
}
</script>

I tried changing create.json(); to JSON.parse(create); and still shows it as undefined, and I am supposed to get the created wallet ID. Yes, the server is giving out a JSON response, something like this: {"id":"examplethinghere"}. By the way, I have searched and none of the questions have helped me either.

Sebastian Simon
  • 18,263
  • 7
  • 55
  • 75
  • See [Why does .json() return a promise?](/q/37555031/4642212) and read the [documentation](//developer.mozilla.org/en/docs/Web/API/Response/json). `JSON.parse(create);` throws an error. You won’t get `undefined` in that case. – Sebastian Simon Dec 18 '22 at 16:15

2 Answers2

2

You need to do await create.json() otherwise createjson will be a promise. meaning createjson.id will simply return undefined because the promise doesn't have an attribute id.

Teddy
  • 452
  • 1
  • 12
  • I also did that too and nothing @Cuong Vu – Jose Moran Urena Dec 18 '22 at 20:12
  • I don't see any other obvious problems with your code. If you have awaited `fetch()` and `json()`. You could check if you revive the json in the format that your expect. This could be tested with [postman](https://www.postman.com/) for example. – Teddy Dec 18 '22 at 20:17
2

The Response.json() method returns a promise. So you need to await it

const createjson = await create.json();

Cuong Vu
  • 3,423
  • 14
  • 16