-1

When running getTicket ()

Alert (JSON.stringify (responseJson));

Data is recovered properly But in listTicket (), the other data is shown to me My code is as follows

getTicket:

async getTicket ()
    {
      try {
        let response = await fetch(
          'url'
        ,{
          method: 'POST',
          headers: {
            'Accept': 'application/json',
            'Content-Type': 'application/json',
          },
          body: JSON.stringify({
            uid: '1',
            type: '0',
          })
        });

        let responseJson = await response.json();
        alert(JSON.stringify(responseJson));
        return responseJson;
      } catch (error) {
        alert(error);
      }

    }

listTicket code:

listTicket()
   {

     let objectTicket = this.getTicket();


     alert(JSON.stringify(objectTicket));
   }

please help

codex
  • 87
  • 1
  • 12
  • 1
    Possible duplicate of [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – JJJ Aug 28 '18 at 11:21
  • @JJJ thanks , I saw the link but did not notice, can you might correct code? – codex Aug 28 '18 at 11:42
  • you don't need return response, just use setState() instead return responseJson; – xadm Aug 28 '18 at 11:45
  • @xadm When I use setState, the listTicket function is placed in the loop – codex Aug 28 '18 at 18:23
  • it shouldn't when called from componentDidMount - it can when ABUSED, called from render and some other lifecycle methods – xadm Aug 28 '18 at 18:28
  • @xadm yes I used the listTicket on the render because I want to display some views dynamically. But when I delete this.setState in getTicket, the loop problem is resolved. What solution would you recommend to resolve the problem? – codex Aug 28 '18 at 18:47
  • it shouldn't be called from render!! fetch (from cDM) receives data and saves in state (setState), updating state forces new render (with new data) – xadm Aug 28 '18 at 18:52
  • @xadm Where should I call listTicket? Before render (), i get an error, thanks – codex Aug 28 '18 at 19:29
  • you don't need `listTicket` at all. call `this.getTicket()` from `componentDidMount`. what kind of error?? – xadm Aug 28 '18 at 19:33
  • @xadm I often need to call the function with different parameters. As far as I know, componentDidMount runs only once. – codex Aug 28 '18 at 19:37
  • make this simple flow working - if there're other requirements then show more, non theoretical code – xadm Aug 28 '18 at 19:43
  • @xadm i used componentDidMount but i get null, i add new post , please help – codex Aug 28 '18 at 20:10

1 Answers1

1

Just call this.getTicket() like this to get the promis returned from the async function:

this.getTicket()()
  .then(function(objectTicket) {
    alert(JSON.stringify(objectTicket));
  });
Laurenz Glück
  • 1,762
  • 3
  • 17
  • 38