-1

I'm writing an app in Reactjs. I want to make an api call when the component/page is opened.

From componentDidMount() I call another function which makes a http request using axios. From that function a want to return an object back to componentDidMount() where i try to print it in the console.

I have tried to put the the code in the http function in to componentDidMount and that works.

export class MyFunction extends Component {
  ...

  functionOne = () => {
    axios.get(API_FETCH_LINK)
      .then(response => response.data)
      .then((data) => {
        console.log("Data from db", data);              //PRINT ONE
        var date = new Date(Date.parse(data.timeStamp));
        console.log("Date from db", date);              //PRINT TWO
        return date;
        });
    };

  componentDidMount(){
  var date = this.functionOne();
  console.log("The date is ", date);                   //PRINT THREE
  }

 ...
}

The output from PRINT ONE and PRINT TWO makes sense, but PRINT THREE shows "undefined". Does anyone see why?

  • you didn't return anything from functionOne, so when you say `var x = functionOne()` from a function that you do'nt return anything from, it's undefined – TKoL Aug 06 '19 at 14:52
  • 1
    You have no `return` in `functionOne()` and axios.get is **asynchronous** – charlietfl Aug 06 '19 at 14:53

1 Answers1

-1
export class MyFunction extends Component {
    functionOne = () => {
        return axios.get(API_FETCH_LINK)
            .then(response => response.data)
            .then(data => {
                console.log("Data from db", data); //PRINT ONE
                var date = new Date(Date.parse(data.timeStamp));
                console.log("Date from db", date); //PRINT TWO
                return date;
            });
    };

    componentDidMount() {
        this.functionOne().then(date => console.log("The date is ", date));
    }
}
Ahmed Saber
  • 489
  • 1
  • 9
  • 21
  • 1
    Why have the `var date = ` at the begging of that? you're setting the variable date to a promise, and then not using it. – TKoL Aug 06 '19 at 14:53
  • He already has it like this, why you blame for something I didn't create – Ahmed Saber Aug 07 '19 at 07:18
  • He clearly already has it like that because he doesn't understand how promises work. It is clearly a mistake and there's no reason to keep it in. – TKoL Aug 07 '19 at 08:53