Home > Software design >  Customising RTK-query query / mutation body with redux store
Customising RTK-query query / mutation body with redux store

Time:11-10

I would like to make the query body using current redux store data in this createApi function changing the postBody variable. I mean I want to get a redux node here from the store and merge the data with postBody if that's possible.

export const loginIdentityApi = createApi({
  reducerPath: 'loginIdentity',
  baseQuery,
  tagTypes: ['Login'],
  endpoints: (build) => ({
    postLogin: build.mutation<TApiResponse, TPostBody>({
      query: (postBody: TPostBody) => ({
        url: urlPrep(signin, {
          updateCookies: true,
        }),
        method: 'POST',
        body: postBody,
      }),

      transformResponse: (response: TApiResponse) => {
        return response
      },
      invalidatesTags: ['Login'],
    }),
  }),
})

CodePudding user response:

This is not possible by design.

If things like that were possible, either your requests and your state would run out of sync, or there would need to be some very complicated tracking logic in place to determine which state change would trigger a refetch.

So, all the data you can get in there is only though the arg.

Get that data in your component and pass it in as an arg instead.

const dataFromStore = useSelector(selectMyDataFromStore)
const result = useMyQuery({ body: dataFromStore })

CodePudding user response:

Thanks for your reply @phry,

I've found this doc on RTK site;

https://redux-toolkit.js.org/rtk-query/usage/customizing-queries#performing-multiple-requests-with-a-single-query

How about this if I use a state like that?

export const shippingInfoApi = createApi({
  reducerPath: 'shippingInfo',
  baseQuery,
  tagTypes: ['ShippingInfo'],
  endpoints: (build) => ({
    putShippingInfo: build.mutation<TApiResponse, TPostBody>({
      async queryFn(_arg, { getState }, _extraOptions, fetchWithBQ) {
        const state = getState()
        const shipModeId = state.shippingOptions.queries['getShippingOptions(null)'].data[0].value;
        await fetchWithBQ({
          url: urlPrep(shippingInfo, {
            updateCookies: true,
          }),
          method: 'PUT',
          body: { ..._arg, shipModeId },
        })
      },
    }),
  }),
})

And also I don't know how I can get the data from this state like

state.shippingOptions.queries['getShippingOptions(null)'].data[0].value

  • Related