Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
173 views
in Technique[技术] by (71.8m points)

javascript - acync await react/redux js async events

https://ibb.co/dsNrnPQ -- screenshot of error

I get a problem with an async event. When logging into the site, when locale-storage is not ready yet. I can't get it async. After refreshing the page, the problem goes away.

Unhandled Rejection (SyntaxError): Unexpected token u in JSON at position 0

Problem in string

const userData = await userDataGetter();

export function setBalanseFetch(){

    return async dispatch => {

        const userData = await userDataGetter();


        const userID = await userData.userId;

        try{
            const respone = await axios.post('/api/profile', {userID})
            const json = await respone["data"];
            const FetchBalanse = json.items[0].balanse;
            dispatch( {type: FETCH_BALANSE, payload: Number(FetchBalanse)})
        }catch(e){
           
            console.log(`Axios spend balanse request failed: ${e}`);
        }
    }
}

code function userDataGetter

async function userDataGetter(){

    const userData = await JSON.parse(localStorage.userData);

    return userData;
}

export default userDataGetter

question from:https://stackoverflow.com/questions/65870336/acync-await-react-redux-js-async-events

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You have:

const userData = await JSON.parse(localStorage.userData);

However, JSON.parse is not an asynchronous function. It does not wait for a localStorage key to be present and ready, which is what your code seems to want it to do. (Also, as a comment pointed out, you want localStorage.get('userData')). Nor are you checking that it is present at all.

You also don't show where the localStorage is getting set. But likely your solution will be to then trigger the code that depends on it after you know its been set from the same place that's setting it, and when you need to access it any other time, check for its presence first.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...