简体   繁体   中英

React redux setting initial state from axios call

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.

You have to return promise from your getUserData function and access it using .then() .

 function getUserData() { return new Promise((resolve, reject) => { if (Auth.loggedIn()) { axios.get('/route') .then(res => resolve(res.data)) .catch(err => reject(err)); } else { resolve(' '); } }); }; getUserData().then(function(userData) { const initialState = { userData: userData, // ' ' or axios result }; console.log(initialState.userData) }); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM