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
208 views
in Technique[技术] by (71.8m points)

javascript - How to return async data in reducer

I'm getting some data from back-end of my app, but I have a hard time returning state properly. Code:

if (action.type === actionTypes.getList) {
    const id = action.payload.userId;
    
    Axios.post(`${apiUrl}/lists`, {
        userId: id,
    })
        .then((response) => {
            const newLists = response.data;
            return { ...listState, lists: newLists };
        })
        .catch((e) => {
            console.log("There has been error: ", e);
        });
}

With this state's reducer state is undefined, and I get it since I'm not returning anything from main If statement.

if (action.type === actionTypes.getList) {
    const id = action.payload.userId;

    const newLists = Axios.post(`${apiUrl}/lists`, {
        userId: id,
    })
        .then((response) => {
            const res = response.data;
            return res
        })
        .catch((e) => {
            console.log("There has been error: ", e);
        });
    return { ...listState, lists: newLists };
}

Here my reducer state is empty object and I get Promise { : "pending" } in console. Is there some way how to call that main return statement after the async function is done? Or any other way of solving this problem?


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

1 Answer

0 votes
by (71.8m points)

I'll advise you to use Redux actions for any middleware logic between the reducer and the dispatch function. see https://redux.js.org/tutorials/fundamentals/part-3-state-actions-reducers I'm not sure what's wrong with your code tho...


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

...