How To Call An Async Function In Non-Async Function
I am new to React Js, and trying to make an API call using fetch
.
I have written a generic async function that I am using to API calls, to send requests to the API Endpoint. That function is being called in another class's function, that should parse the result and return the value to the parent function calling.
Here is my utility class with a function that calls the endpoint:
export default class RestUtil {
getModel = async (model) => {
let url = 'http://api.xyz.com/' + model;
const apiCall = await fetch(url,
{
method: 'GET',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
'Authorization': 'Bearer xyz'
}
});
return apiCall.json();
}
}
Below is my React Component that is causing issues:
export default class MyComponent extends React.Component {
componentDidMount() {
this.populateUsersDropDown();
}
populateUsersDropDown() {
let users = this.fetchUsers();
// Here the `users` is undefined. <-------- Issue
//Do some other work with users
/*Populate users in
the dropdown*/
}
fetchUsers() {
new RestUtil()
.getModel('users')
.then(data => {
/* Do some other work with data */
return data;
})
}
}
Now I want the populateUsersDropDown() to wait for the fetchUsers() to complete it's then
part and return the data and proceed. But I am receiving undefined
in users variable. Wheres, in my then
section, I am able to see the data.
Need some help in solving this please?
Answer
Your fetchUsers
method does not return anything.
async fetchUsers() {
const users = await new RestUtil().getModel('users');
return users;
}
This should work
Related Questions
- → How to update data attribute on Ajax complete
- → October CMS - Radio Button Ajax Click Twice in a Row Causes Content to disappear
- → Octobercms Component Unique id (Twig & Javascript)
- → Passing a JS var from AJAX response to Twig
- → Laravel {!! Form::open() !!} doesn't work within AngularJS
- → DropzoneJS & Laravel - Output form validation errors
- → Import statement and Babel
- → Uncaught TypeError: Cannot read property '__SECRET_DOM_DO_NOT_USE_OR_YOU_WILL_BE_FIRED' of undefined
- → React-router: Passing props to children
- → ListView.DataSource looping data for React Native
- → Can't test submit handler in React component
- → React + Flux - How to avoid global variable
- → Webpack, React & Babel, not rendering DOM