This question already has an answer here:
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?
Aucun commentaire:
Enregistrer un commentaire