redux-toolkit icon indicating copy to clipboard operation
redux-toolkit copied to clipboard

Race conditions when using updateQueryData

Open yankinx opened this issue 1 year ago • 1 comments

A similar issue with "invalidate tags" was fixed in https://github.com/reduxjs/redux-toolkit/pull/3116

  1. If request Q has started
  2. Mutation M started and finished, there should be an pessimistic update of the cached data.
  3. Once request Q finishes, it should have an pessimistic update.

If you perform updateQueryData on request Q which is in a pending status, then no changes will be made.

If you perform updateQueryData on request Q which is in a pending status, then after the completion of request Q, no changes will be made.

In my opinion, this is not correct, as it limits pessimistic updates which encourages the use of invalidatesTags, an additional request I do not want to make, because I already have the necessary data in the response from the mutation.

an example of how I try to perform an pessimistic update

const ridesApi = createApi({
  baseQuery,
  endpoints: builder => ({
    getRides: builder.query({
      query: () => 'rides'
    }),
    postRidePrice: builder.mutation({
      query: id => ({
        url: `ride/${id}`,
        method: 'POST'
      }),
      async onQueryStarted(arg, { dispatch, queryFulfilled }) {
        try {
          const { data } = await queryFulfilled;

          /* 
          this is a part of the code that helps to fix the problems described above, but it has a flaw in the expectation
          const res = dispatch(ridesApi.util.getRunningQueryThunk('getRides', undefined));

          if (res) {
            await res;
          }
          */

          dispatch(
            ridesApi.util.updateQueryData('getRides', undefined, rides => {
              const ride = rides.find(ride => ride.id === data.id);

              if (ride) {
                Object.assign(ride, data);
              }
            })
          );
        } catch (e) {
          console.error(e);
        }
      }
    })
  })
});

yankinx avatar Mar 13 '24 02:03 yankinx