1

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?

3
  • 1
    use async await in populateUsersDropDown Commented Nov 13, 2019 at 10:24
  • 1
    you can take a look at stackoverflow.com/a/58815843/5124488 ? I recommend using Axios Commented Nov 13, 2019 at 10:25
  • You should use a state variable and update it when API returns data. This will simplify things. Commented Nov 13, 2019 at 10:28

1 Answer 1

1

Your fetchUsers method does not return anything.

    async fetchUsers() {
     const users = await new RestUtil().getModel('users');

     return users;
   }

This should work

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.