0

I have a strange problem that keeps me scratching my head. I'm trying to get data from a api and pass the returned data to a component (as a prop) with React Router. However the returned data is 'undefined'.

MyRoutes.js:

let refreshAvailability = (profile_index) => {
    let fetch = new DataFetch();
    fetch.get(`/info/${profile_index}`, (err, res) => {
        let username = res[Object.keys(res)[0]].username;
        if(username !== undefined) {
            setTimeout(() => {return getStatus(username)}, 0);
            setInterval(() => {return getStatus(username)}, 10000); //Refresh every 10 seconds
        }
    });
}

let getStatus = (username) => {
    let userStatus = new userStatus();
    userStatus.getStatus(available => {
        //If i place console.log(available) here it will print the result, but when i return it, its undefined.
        return available;
    });
}

const myRoutes = () => (
  <BrowserRouter>    
            <Route exact path='status/:profile_index' render={(props) => (
                <Status {...props} available={refreshAvailability} />
            )}/>
  </BrowserRouter>
);

export default MyRoutes;

Status.js:

componentDidMount(){
    let userIndex = this.getUserIndex();
    let userStatus = this.props.available(userIndex);

    console.log(userStatus); //This prints undefined
}

Somehow the problem seems to be in the getStatus function. If i log the output of the api there i can see it logging in the Status component, but when i return it it returns 'undefined'.

This leaves me to the question how React is handling functions with a return statement as a prop? Is it any different than passing a function without return? Or am i overlooking things in my code?

Mitch
  • 715
  • 4
  • 12
  • 28
  • `refreshAvailability` **doesn't** return anything. The callback function you're passing into `get` returns something, but `refreshAvailability` doesn't. And moreover, it *can't* return the result of the `get` operation, because that operation is only **started** by calling `get`. It finishes later, after `refreshAvailability` has already returned. See the linked question's answers for a fuller explanation and for how to fix it (I'd use a promise). – T.J. Crowder Feb 03 '18 at 18:45
  • 1
    @T.J.Crowder Thanks for helping me set a step in the right direction. I will turn my focus on resolving it with a promise. Learning something new everyday :) – Mitch Feb 03 '18 at 19:02
  • My pleasure. This is something nearly *everyone* runs into and doesn't understand at first. Happy coding! – T.J. Crowder Feb 03 '18 at 19:10

0 Answers0