How to implement an optimistic update when using reduxjs/toolkit

Viewed 288

My reducer file is below

const slice = createSlice({
  name: "hotels",
  initialState: {
    list: [],
    loading: false,
    lastFetch: null,
  },
  reducers: {
    hotelsRequested: (hotels) => {
      hotels.loading = true;
    },
    hotelsRequestFailed: (hotels) => {
      hotels.loading = false;
    },
    hotelsReceived: (hotels, action) => {
      hotels.list = action.payload;
      hotels.loading = false;
      hotels.lastFetch = Date.now();
    },
    hotelEnabled: (hotels, action) => {
      const { slug } = action.payload;
      const index = hotels.list.findIndex((hotel) => hotel.slug === slug);
      hotels.list[index].active = true;
    },
  },
});

export const {
  hotelsReceived,
  hotelsRequestFailed,
  hotelsRequested,
  hotelEnabled,
} = slice.actions;
export default slice.reducer;

//Action creators
export const loadHotels = () => (dispatch, getState) => {
  const { lastFetch } = getState().entities.hotels;
  const diffInMinutes = moment().diff(lastFetch, "minutes");
  if (diffInMinutes < 10) return;
  dispatch(
    hotelApiCallBegan({
      url: hotelUrl,
      onStart: hotelsRequested.type,
      onSuccess: hotelsReceived.type,
      onError: hotelsRequestFailed.type,
    })
  );
};

export const enableHotel = (slug) =>
  hotelApiCallBegan(
    {
      url: `${hotelUrl}${slug}/partial-update/`,
      method: "put",
      data: { active: true },
      onSuccess: hotelEnabled.type,
    },
    console.log(slug)
  );

My api request middleware function is as follows

export const hotelsApi = ({ dispatch }) => (next) => async (action) => {
  if (action.type !== actions.hotelApiCallBegan.type) return next(action);

  const {
    onStart,
    onSuccess,
    onError,
    url,
    method,
    data,
    redirect,
  } = action.payload;

  if (onStart) dispatch({ type: onStart });

  next(action);
  try {
    const response = await axiosInstance.request({
      baseURL,
      url,
      method,
      data,
      redirect,
    });

    //General
    dispatch(actions.hotelApiCallSuccess(response.data));
    //Specific
    if (onSuccess) dispatch({ type: onSuccess, payload: response.data });
  } catch (error) {
    //general error
    dispatch(actions.hotelApiCallFailed(error.message));
    console.log(error.message);
    //Specific error
    if (onError) dispatch({ type: onError, payload: error.message });
    console.log(error.message);
  }
};

Could anyone point me in the right direction of how to add an optimistic update reducer to this code. Currently on hitting enable button on the UI there's a lag of maybe second before the UI is updated. Or maybe the question, is do i create another middleware function to handle optimistic updates? If yes how do i go about that? Thanks

0 Answers
Related