Sharon Chai
Sharon Chai

Reputation: 517

async await in componentDidMount returned strange value

Anything wrong with below code? Trying to fake a fetch using setTimeout.

getData = () => {
    return setTimeout(() => {
      return new Promise(resolve => resolve(
        [
          {
            id: 1,
            name: "Cat",
          },
        ]
      ))
    }, 500)
  }

  async componentDidMount() {
    this.setState({
      loading: true
    })

    const data = await this.getData()
    console.log('uh', data)

  }

getDate returned randomed value, I wonder where does that come from.

https://codesandbox.io/s/m9zp588o0x

Upvotes: 0

Views: 41

Answers (1)

Artem Mirchenko
Artem Mirchenko

Reputation: 2170

Set timeout must be in promise body:

 getData = () => {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      resolve(
        [
          {
            id: 1,
            name: "Cat"
          }
        ]
      );
    }, 500)
  })
}

You need return promise, instead you returning setTimeout function.

Upvotes: 3

Related Questions