0

I have a file with some functions:

const API = {
async getComments() {
   var data = [];
   var url = 'http://url.com/wp-json/wp/v2/comments';
   const serviceResponse = await fetch(
    url,
    )
    .then((serviceResponse) => {
     return serviceResponse.json();
   } )
    .catch((error) => console.warn("fetch error:", error))
    .then((serviceResponse) => {
      for (i in serviceResponse) {
        data.push({
         "key": serviceResponse[i]['id'].toString(),
         "name": serviceResponse[i]['author_name'],
         "content": serviceResponse[i]['content']['rendered'].replace(/<(.|\n)*?>/g, ''),
         "gravatar": serviceResponse[i]['author_avatar_urls']['96'],
         "date": serviceResponse[i]['date'].replace('T', ' ')
        });
      }
      global.comments = data;
      return data;
   });
 }
}

export { API as default }

In another file I include the file, and make the call:

var comments = await API.getComments(key);
console.log (comments);

But I receive undefined, I tried to create a function with bind: this.newGetComments = API.getComments.bind(this); with the same result. I used a global variable, but I want to remove the globals vars.

3
  • Hi @Enrique, what you have received undefined. global variable? or getComments() ? Commented Dec 10, 2019 at 5:18
  • 2
    You forgot to return data in getComments. Try return serviceResponse at the end of getComments Commented Dec 10, 2019 at 5:28
  • Thank you, I had the return in a wrong line, sorry I didn't see that detail Commented Dec 10, 2019 at 15:09

3 Answers 3

1

/* Few suggestions;
1. you  are not returning anything from the getComments method. Please return fetch(url) response.
2. you should return  something from the catch block to handle the error.
*/


const API = {
  async getComments() {
    var url = 'http://url.com/wp-json/wp/v2/comments';
    var response = await fetch(url)
      .then(serviceResponse => {
        return serviceResponse.json();
      })
      .then(serviceResponse => {
        let data = [];
        
        // rest of your code.
        
        return { success: true, data };
      })
      .catch(error => {
        console.warn('fetch error:', error);
        return { success: false, error };
      });
    return response
  },
};

var comments = await API.getComments(key);
if (comments.success) {
  // handle the success case  comments.data
} else {
  // handle the Error case  comments.error
}

console.log(comments);

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

1 Comment

I am sorry, yes the return was in a wrong line, thank you. I'll add a response in error case
0

An async function always returns a promise as you aren't returning anything from the getComments methods, the function automatically resolves and returns undefined(Promise.resolve(undefined)). You need to return serviceResponse from the getComments method to get the fetch api's response.

Comments

0

You can try something like below:

async componentDidMount() {
   let data = [];
   const result = await this.getComments();
   const jsonData = await result.json();
   console.log('Result ==> ', jsonData.serviceResponse);

   jsonData.serviceResponse.map(data => 
      data.push({
                 "key": data['id'].toString(),
                 "name": data[i]['author_name'],
                 "content": data[i]['content']['rendered'].replace(/<(.|\n)*?>/g, ''),
                 "gravatar": data[i]['author_avatar_urls']['96'],
                 "date": data[i]['date'].replace('T', ' ')
               })
   );
   console.log('Data ==> ', data);
}

async getComments() {
   const result = await fetch('http://url.com/wp-json/wp/v2/comments', {method: 'GET'});
   return result;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.