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.
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)
}
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.