0

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:

enter image description here

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;
    });
Shail
  • 83
  • 3
  • 11
  • You could do an optimistic update and rollback if the api call fails. Optimistic updates can be dangerous because if the user left the screen before the api call fails it is difficult to notify the user something went wrong. You could also show a loading animation by dispatching loading before the api call and dispatching success/failure after but this will give you a less responsive UI (still better than lagging). – HMR Oct 25 '21 at 10:50
  • @HMR because of the reasons you mentioned, i am not willing to go through that approach – Shail Oct 25 '21 at 15:02
  • 2
    @Shail If you want to update the UI immediately to feel fast and responsive AND persist the change in the backend, optimistic update is the only way unfortunately. The problem of the user navigating away from this screen and not knowing that their drag and drag action couldn't be saved in the backend is usually solved by some type of global notification/toast component that can pop up anywhere and inform the user about a problem. – timotgl Oct 25 '21 at 15:19

0 Answers0