0

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'],
    }),
  }),
})
Lin Du
  • 88,126
  • 95
  • 281
  • 483
superdem
  • 15
  • 1
  • 4

2 Answers2

2

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 })
phry
  • 35,762
  • 5
  • 67
  • 81
0

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

superdem
  • 15
  • 1
  • 4
  • For the reasons in my answer I would really recommend doing that. This is technically possible, but I really recommend against it. – phry Nov 10 '21 at 14:34