Artun Burak Mecik
Artun Burak Mecik

Reputation: 33

React-Native app async data retrive not working properly

I used the componentDidMount method as async and made some operations, but the system returned to me the state of the first entry instead of working async.

  async componentDidMount() {
    await this.getCityList();
    console.log(this.state.cities)
    await this.currentLocation();
  }

At this point the console log turns empty. however, when I normally check, data input is observed, but comes after a while. The same applies to the currentloc method. These methods draw some data from the database.

and city function:

  getCityList() {
    let link = "http://..../Cities";
    fetch(link)
      .then(response => response.json())
      .then(res => {
        this.setState({
          cities: res,
        })
      })
      .catch(error => console.warn(":::::::::", error));
  }

Upvotes: 0

Views: 55

Answers (1)

Umair Sarfraz
Umair Sarfraz

Reputation: 5953

You need to return the Promise inside getCityList method.

Without return:

async function foo() {
  const result = await baz();
  console.log('Result', result);

  console.log('Should be called after baz!');
}

function baz() {
  new Promise((resolve) => {
    setTimeout(() => resolve('Hello from baz!'), 3000);
  });
}

foo();

With return:

async function foo() {
  const result = await baz();
  console.log('Result', result);

  console.log('Should be called after baz!');
}

function baz() {
  return new Promise((resolve) => {
    setTimeout(() => resolve('Hello from baz!'), 3000);
  });
}

foo();

Following is the correct way to do it for await to work (with your example snippet):

 getCityList() {
    let link = "http://..../Cities";
    return fetch(link) // Added a return here
      .then(response => response.json())
      .then(res => {
        this.setState({
          cities: res,
        })
      })
      .catch(error => console.warn(":::::::::", error));
  }

Upvotes: 2

Related Questions