1

I'm trying to build a react application and with axios and it doesn't work as I expect... I guess its async Problem, that my return doesn't wait for the call to be finished...

The structure of my files may seem a bit weird, but I need to do it like that (not allowed to change it...)...

My Component: (It will always console log "not set"

import * as api from '../../services/home/HomeController';
.......
// Some other stuff in this section
.......
  componentDidMount() {
    var result = api.getAll();
    this.setState({
      data1: result
    });
  }
  ..........
render() {
  if(this.state.data1 === undefined) {
    console.log("not set");
  }
  else {
    console.log(this.state.data1);
  }
}

My HomeController:

import { fetchData } from '../axios/axios';

export const getAll = () => {
  return fetchData('https://myAPIUrl'); //removed the correct URL
};

The axios function: import axios from 'axios';

export const fetchData = (url) => {
  axios.get(url)
    .then(res => {
      console.log("Axios returning result...");
      //console.log(res.data); //When I un-comment this line, I get the result logged in the console
      return res.data;
    });
}

So as you see, the result gets logged in the console in the axios component, since this function hat a promise and wait the call to be finished. But I guess the return on HomeController doesn't do that, I am right?

Pretty new to JS, kinda confusing this whole ASYNC thing... What would be the best solution for my problem?

Thank you for your help ! :)

Twinfriends
  • 1,972
  • 1
  • 14
  • 34

0 Answers0