Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

async/await not working in reactjs (used npx create-react-app) [duplicate]

Currently, the console.log() in makeQuery() is returning the correct object while the console.log() in scoop() is returning "undefined" as the definition of response in scoop() is not waiting for the function call to makeQuery() to return.

I would like for the definition of response in scoop() to wait for the function call to makeQuery() before the code below runs.

How do I make this happen?

var request = require('request');

const makeQuery = (query) => {
  request('http://0.0.0.0:4000/wikiweb?text=' + query, function (error, response, body) {
      var jason = JSON.parse(body)
      console.log(jason)
      return jason
    }
  )

class Wiki extends React.Component {



  constructor (props) {
    super(props)
    this.scoop = this.scoop.bind(this);
    this.state = {loaded: false}
  }

  scoop = async (e) => {
    e.preventDefault();
    var query = this.textInput.value;
    var response = await makeQuery(query);
    console.log(response)
    // await this.setState({data : response, loaded : true});
    // console.log(this.state.data)
  } 

...
like image 793
Tadeo Yelos Avatar asked Mar 27 '26 06:03

Tadeo Yelos


1 Answers

You have to return a promise from the makeQuery function or there will be no promise to use await on and it will resolve immediately.

Example

const makeQuery = query => {
  return new Promise(resolve => {
    request("http://0.0.0.0:4000/wikiweb?text=" + query, function(
      error,
      response,
      body
    ) {
      var json = JSON.parse(body);
      console.log(json);
      resolve(json);
    });
  });
};

class Wiki extends React.Component {
  constructor(props) {
    super(props);
    this.scoop = this.scoop.bind(this);
    this.state = { loaded: false };
  }

  scoop = async e => {
    e.preventDefault();
    var query = this.textInput.value;
    var response = await makeQuery(query);
    console.log(response);
  };

  // ...
}
like image 126
Tholle Avatar answered Mar 28 '26 18:03

Tholle