3

I try to find my way around in JavaScript and the React Native Framework:

Basically what I am trying is to speak with an API via fetch, so I set up an AsyncFunction:

class MyComponent extends React.Component {
     async getToken(client_id, client_key, username, password) {
        try {
        let response = await fetch('https://expample.com/o/token/', {
            method: 'POST',
            body: JSON.stringify({
              client_id: client_id,
              client_secret: client_key,
              grant_type: 'password',
              username: username,
              password: password,
            })
          });
          let responseJson = await response.json();
          return responseJson.access_token;
        } catch(error) {
          console.error(error)
        }
      }
...
}

But now I have no idea how to call this function.

var token = getToken.token

just gives a syntax error and

'token': getToken.token

also doesn't do the trick.

Daniel Beck
  • 20,653
  • 5
  • 38
  • 53
Maximilian Kindshofer
  • 2,753
  • 3
  • 22
  • 37
  • Possible duplicate of [How do I return the response from an asynchronous call?](http://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – CBroe Mar 31 '16 at 20:53
  • Well I dont think this is my problem since I cant even declare a var in the component object... – Maximilian Kindshofer Mar 31 '16 at 20:57

1 Answers1

4

You can assign the response to the component's state like so:

class MyComponent extends React.Component {
  constructor(props) {
    super(props);
    this.state = { token: null, };
  }

  async getToken(client_id, client_key, username, password) {
    try {
    let response = await fetch('https://example.com/o/token/', {
        method: 'POST',
        body: JSON.stringify({
          client_id: client_id,
          client_secret: client_key,
          grant_type: 'password',
          username: username,
          password: password,
        })
      });
      let responseJson = await response.json();
      this.setState({ access_token: responseJson.access_token });
    } catch(error) {
      console.error(error)
    }
  }
}
QMFNP
  • 997
  • 8
  • 14
  • 1
    how to separate the async function and set a variable then? like in index.js token=getToken(username,password) and getToken is a method of token.js? – Milon Sep 08 '17 at 13:07