1

I'm having trouble storing the result from this fetch to an array:

const words = []
fetch("https://random-word-api.herokuapp.com/word?number=100")
  .then(response => response.text())
  .then(result => console.log(result))
  .then(function (data) {
    for (var i = 0; i < result.length; i++) {
      words.push(data.result[i])
      console.log(words)
    }
  })
  .catch(error => console.log('error', error));
let promise = fetch("https://random-word-api.herokuapp.com//word?number=10")

2 Answers 2

1

Firstly you want to call response.json() instead since the data returned is json
The data is in the result parameter after, you can iterate through this array to get the words.

const words = []
fetch("https://random-word-api.herokuapp.com/word?number=100")
  .then(response => response.json())
  .then(function (result) {
    console.log('Result', result)
    for (var i = 0; i < result.length; i++) {
      words.push(result[i])
    }
    console.log('Words', words)
  })
  .catch(error => console.log('error', error));

Sign up to request clarification or add additional context in comments.

Comments

0

The way you're planning on storing the words array might be problematic because you can't control how long the fetch will take.
Usually you'd store the result of the promise in a variable an control that after the promise has settled:

const words = fetch("https://random-word-api.herokuapp.com/word?number=100")
  .then(response => response.json())


words
  .then(x => {
    console.log('the promise has settled', x)
  })
  .catch(console.error)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.