Multiple/bulk delete in react + redux

馋奶兔 提交于 2019-12-25 03:17:53

问题


I have a data grid that allows multiple selection and deletion feature. I have a delete endpoint from my api;

DELETE http://localhost:8888/api/audit/id

And this is the action creator;

export function deleteAudit(audits, callback) {
    let count = 0;
    console.log("selected audits", audits);

    const deleteItem = (auditId) => {
        console.log("deleting..", auditId);

        const endpoint = `http://localhost:8888/api/audit/${auditId}`;
        const req = Axios.delete(endpoint, callback);
        return (dispatch) => {
            req.then(res => {
                if (res.status == HttpStatus.OK) {
                    console.log("deleted", auditId);
                    count += 1;
                    if (audits[count] != null) {
                        deleteItem(audits[count]);
                    }
                    else {
                        console.log("all deleted heading to callback");
                        callback();
                    }
                }
            });
            dispatch({type:DELETE_AUDIT, payload: audits});
        }
    }
    deleteItem(audits[count]);
}

As my endpoint just allows one item deletion at a time, I used a recursive function to make calls successively. However, this ain't work properly when ignore using async(thunk) approach, it was not refreshing list with new state. After adding the thunk dispatch method it only deletes the first selection, so I get completely lost. What is the right way to achieve this?


回答1:


The problem was, I didn't import the redux-thunk package, after importing it, as @Tho Vu pointing out on axios, I have changed my code as follows;

export const deleteAudit = (audits, callback) => {

    const request = axios.all(_.map(audits, (audit) => 
    {   
        deleteItem(audit);
    }));
    return (dispatch) => {
        request.then(axios.spread((a, f) => {
            dispatch({type:DELETE_AUDIT, payload:audits});
        })).then(() => {
            callback();
        });
    }
}
function deleteItem(id) {
    const endpoint = `http://localhost:8888/api/audit/${id}`;
    return axios.delete(endpoint);
}


来源:https://stackoverflow.com/questions/52495292/multiple-bulk-delete-in-react-redux

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!