0

In React ... I am trying to read the response return from API and get undefined, what is the problem?

Undefined occurs when calling the function retrieveItems() from the component.

**// item service class** 
import axios_o from 'axios';

class ItemService {
  retrieveItems() {
    axios_o.get("https://jsonplaceholder.typicode.com/posts")
      .then(response => {
        return  response;
      }).catch();
  }
}
**// component calling the item service** 
import React from 'react'
import ItemService from "../Services/ItemService";

class Posts extends React.Component {
  constructor(props) {
    super(props);
  }

  componentDidMount = () => {
    this.itemservice=new ItemService();
    **console.log(this.itemservice.retrieveItems())**
  }

  render() {
    return (
      <h1>Posts List</h1>
    );
  }
}

export default Posts;
Emile Bergeron
  • 17,074
  • 5
  • 83
  • 129
DeVYaGhI
  • 31
  • 7

3 Answers3

2
class ItemService {
 retrieveItems() {
   return axios_o.get("https://jsonplaceholder.typicode.com/posts")
     .then(response => response)
     .catch(error => error)      
  }
}
componentDidMount = () => {
  this.itemservice=new ItemService();
  this.itemservice.retrieveItems().then(res=>{
    console.log(res);
  }).catch(error=>{
    console.log(error)
  });
}
aviya.developer
  • 3,343
  • 2
  • 15
  • 41
  • the added return won't make this any more synchronous, will it? – Christian Fritz Jan 24 '20 at 16:53
  • thanks aviya for your answer , I have a question . can we say that we must use "then" in case of calling function that contains API call ? – DeVYaGhI Jan 24 '20 at 20:18
  • 1
    @DeVYaGhI Well the `then` part is mandatory because of the ajax call. I can't think of any API call that would not be ajax since that would mess up the application always waiting for a server response. So probably the then is needed. – aviya.developer Jan 24 '20 at 22:33
  • 1
    @aviya.developer Many thanks my problem solved – DeVYaGhI Jan 25 '20 at 20:42
0

As I mentioned in the comment the method retrieveItems is not returning a value. To fix this return the axios call

retrieveItems() {
       return axios_o.get("https://jsonplaceholder.typicode.com/posts")
             .then(response => {
                 return  response;
             }).catch(
         );
}

or rewrite it to async/await for better readability

async retrieveItems() {
  try {
    return await axios_o.get("https://jsonplaceholder.typicode.com/posts")
  }catch(e) {
    // do some error handling or move the try/catch to caller side
  }
}

Now in your console log you should see not the real response of the API call but a Promise. To get the real response you also have to wait for the answer on caller side:

class Posts extends React.Component {

    constructor(props) {
        super(props);

    }

    componentDidMount = () => {
        this.retrieveItems()
    }

    retrieveItems = async () => {
        this.itemservice=new ItemService();        
        const response = await this.itemservice.retrieveItems()
        console.log(response)
    }


    render() {
        return (
            <h1>Posts List</h1>
        );

    }
}

With this you should see the response in the console log.

Auskennfuchs
  • 1,577
  • 9
  • 18
0

The issue is the typical pitfall of wanting to return something from within a callback function to the outer function. That's can't work, because the outer function (retrieveItems) has already finished. You need to stay in the asynchronous pattern. The easiest is probably this:

import axios_o from 'axios';

class ItemService {
  retrieveItems() {
    return axios_o.get("https://jsonplaceholder.typicode.com/posts");
  }
}


import React from 'react'
import ItemService from "../Services/ItemService";

class Posts extends React.Component {

  componentDidMount = () => {
    this.itemservice = new ItemService();
    this.itemservice.retrieveItems().then((res) => {
        console.log(res);
    });        
  }

  render() {
    return (<h1>Posts List</h1>);
  }
}

export default Posts;
Christian Fritz
  • 20,641
  • 3
  • 42
  • 71