I am new to React and working on a drag and drop feature and in that I have to send a api request to backend on the drag end and also I need to update the state.
To achieve this I am using redux-toolkit createAsyncThunk
.
On drag end action is dispatched in which backend api is called and then in redux store, inside extraReducres
the state is updated. Updating state in this way is causing lag in state update and causing very poor user experience.
Refer the image for bug:
Sample code:
// Component code
const onDragEnd = () => {
//reordering logic
dispatch(updateDragNDrop(newOrderObjArray));
}
//Async Thunk Code
export const updateDragNDrop = createAsyncThunk(
"todoBlockSlice/updateStateAfterDragNDrop",
async (sections: any) => {
let sectionsArr = [ sections.src, sections.dest]
await axios.post("http://localhost:8080/updateDnd", sectionsArr);
return sections;
}
);
// Extra Reducers Code
builder.addCase(updateDragNDrop.fulfilled, (state, action) => {
let src: TodoSectionType = action.payload.src;
let dest: TodoSectionType = action.payload.dest;
let newSectionsState: TodoSectionType[] = state.sections.map(
(sec: TodoSectionType) => {
if (sec.sectionType === src.sectionType) {
let section: TodoSectionType = {
...src,
};
return section;
} else if (dest !== null && sec.sectionType === dest.sectionType) {
let section: TodoSectionType = {
...dest,
};
return section;
}
return sec;
}
);
state.sections = newSectionsState;
});