I have a React app which uses Redux and axios. I do not want anything to render before I have some information from the server, which I am retrieving via axios.
I thought that the best way to do this would be by initializing redux state based on that axios call.
However, my function does not seem to be returning anything in time for state initialization...
function getUserData() {
if (Auth.loggedIn()) { //leaving this here bc it could be important; Auth is another class and loggedIn returns a boolean
axios.get('/route').then(res => {
console.log(res.data); //This prints the right thing (an object)
return res.data;
});
} else {
return ' '; //This works fine; state gets initialized to ' '
}
}
let userData = getUserData();
console.log(userData); //When getUserData() returns ' ', this prints ' '. However, when getUserData() returns my object, this prints undefined.
const initialState = {
userData: userData
};
I realize that this could be a problem with getUserData() being asynchronous, and console.log(userData) running before getUserData() has finished. However, I tried:
getUserData().then(function(userData) {
console.log(userData);
});
And received 'TypeError: Cannot read property 'then' of undefined'. My function is obviously not returning a promise, so doesn't that mean it's not asynchronous?
Any ideas?
Alternatively, is there a better way of doing this? I could always set initial state and then immediately change it, and make rendering wait for the change to be complete with a conditional render, but that definitely seems worse.