-1

Why I get this error on RTK Query when using onQueryStarted ? When I remove onQueryStarted then it works...

 Possible Unhandled Promise Rejection (id: 0):
TypeError: Cannot destructure undefined
import { createApi, fetchBaseQuery } from "@reduxjs/toolkit/dist/query/react";
// @ts-ignore
import { API_ENDPOINT } from '@env';
import { IProduct } from "../../../components/Product";

export const WishlistApi = createApi({
  reducerPath: 'WishlistApi',
  baseQuery: fetchBaseQuery({baseUrl: `${API_ENDPOINT}/`}),
  tagTypes: ['WISHLIST', 'HOME'],
  endpoints: (build) => ({

    homeList: build.query<(IProduct & { is_wishlist: boolean; })[], void>({
      query: (data) => ({
        url: '/home',
        method: 'POST',
        body: data
      }),
      providesTags: ['HOME']
    }),

    removeWishlist: build.mutation<void, void>({
      query: () => ({
        url: '/remove_wishlist',
        method: 'POST',
        body: 1
      }),
      async onQueryStarted({  }, { dispatch, queryFulfilled }) {
        console.log(queryFulfilled);
        const patchResult = dispatch(
          WishlistApi.util.updateQueryData('homeList', undefined, (draft) => {
            console.log(draft);
          })
        )
        try {
          await queryFulfilled
        } catch {
          patchResult.undo()
        }
      },
      invalidatesTags: ['WISHLIST']
    })
  })
});

export const {
  useHomeListQuery,
  useRemoveWishlistMutation
 } = WishlistApi;

i am very thankful for your help!!

.,.,.,.,.,.,.,.,.,.,.,.,.,.,.,.,.,.,.,.,.,.,.,.,.,.,.,.,.,.,.,.,.,.,.,.,.,.,.,.,.,.,.,.,.,.,.,.,.,.,.,

locklock123
  • 197
  • 1
  • 13
  • Try moving all asynchronous code/logic into a `try/catch`. Are you really just wanting the `homeList` query to run again when the `removeWishlist` mutation is complete? – Drew Reese Nov 19 '22 at 09:40
  • Stuff like this usually happens if you forget to add the middleware or the reducer to your store. – phry Nov 19 '22 at 12:19

1 Answers1

1

I think you have a typo

change this : onQueryStarted({ }, { dispatch, queryFulfilled })

to this: onQueryStarted(arg, { dispatch, queryFulfilled })

you do not send any params with your query so arg is undefined but you trying to destruct the undefined with this { }

Amir Rezvani
  • 1,262
  • 11
  • 34