Personalizing the RTK-query query or mutation body using Redux store

I am trying to incorporate the body query with the help of current redux store data within the createApi function by updating the postBody variable. My objective is to access a specific redux node from the store and integrate its data with postBody, if feasible.

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'],
    }),
  }),
})

Answer №1

It is not within the realm of possibility as per the design.

If such scenarios were feasible, there would be a risk of your requests and the current state getting out of synchronization, or complex tracking mechanisms would be essential to determine which state change should trigger a refetch.

Hence, the only way to access the data is through the argument.

Retrieve the necessary data in your component and pass it as an argument instead.

const storedData = useSelector(selectStoredData)
const updatedResult = useCustomQuery({ params: storedData })

Answer №2

Thank you for responding @phry,

I came across this document on the RTK website;

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

What do you think about using a state like this?

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 },
        })
      },
    }),
  }),
})

Additionally, I am unsure how to access the data from this state like

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Angular2 form builder generating dynamic forms based on results of asynchronous calls

When creating my form, I encountered a challenge with passing the results of an asynchronous call to the form builder. This is what I have attempted: export class PerformInspectionPage implements OnInit { checklists: any; inspectionform: FormGroup; n ...

Question about Redux Toolkit's Entity Adapter: What is the best way to define the selectId type for the update operation?

I am currently learning how to utilize createEntityAdapter in a real-world scenario and I'm encountering difficulties resolving the selectId for Update functions accurately. Here is the working sandbox code: https://codesandbox.io/s/createentityadapt ...

A function that logs a message to the console if an array contains identical values

Struggling to find equal values in my array, I've attempted several methods without success. One approach I tried involved sorting the array: var sorted_arr = this.variacaoForm.value.variacoes.sort(); // the comparing function here for (var i = 0; ...

A specialized type that guarantees a string union includes a particular string literal

I need to define a Mapped type that specifies a field named status which can be either a string or the string value ready: This example works as expected: export type ValidServiceState = HasReady<{ status: "ready" }>; The following should ...

Will the async pipe activate onPush change detection in Angular?

I have searched various sources for the question above, but I am finding conflicting answers. For example, on Angular University's website, it is mentioned that change detection is triggered when the async pipe receives a new observable value. However ...

In the process of developing a custom Vue component library with the help of Rollup and VueJS 3

My goal is to develop a custom Vue component library using rollup and Vue.js. The process went smoothly with Vue2, but I encountered issues parsing CSS files with Vue3. To address this, I updated the dependencies in the package.json file. package.json { ...

What is the best approach to defining a type for a subclass (such as React.Component) in typescript?

Can someone help me with writing a type definition for react-highlight (class Highlightable)? I want to extend Highlightable and add custom functionality. The original Highlightable JS-class is a subclass of React.Component, so all the methods of React.Com ...

Exploring the difference between loop and stream patterns in Azure Service Bus message receiving operations

I am currently setting up the Azure Service Bus messaging infrastructure for my team, and I am working on establishing best practices for developing Service Bus message receivers. We are in the process of creating a new service to consume the Service Bus m ...

Is it possible to utilize types as constants in a switch statement?

In my file called checkoutTypes.ts, I have defined some checkout types like this: export type CheckoutInvoiceAddressSection = "InvoiceAddress"; export type CheckoutDeliveryAddressSection = "DeliveryAddress"; export type CheckoutDelivery ...

`Is there a way to repurpose generic type?`

For instance, I have a STRING type that is used in both the test and test2 functions within the test function. My code looks like this: type STRING = string const test = <A = STRING>() => { test2<A>("0") } const test2 = <B& ...

Storing Json data in a variable within Angular 2: a step-by-step guide

https://i.sstatic.net/2QjkJ.png Within the params.value object, there are 3 arrays containing names that I need to extract and store in a variable. I attempted to use a ForEach loop for this purpose, but encountered an issue. Can you spot what's wron ...

Definition file in TypeScript for an npm package provided by an external source - constructor

In my Node project, I am utilizing ES6 and Typescript. Despite this, there is a commonjs library that I need to incorporate. To address this, I have created my own .d.ts declaration file for the library: module "@alpacahq/alpaca-trade-api" { e ...

Merging Type-GraphQL and Typegoose through a Variety of Decorators

Using a combination of Type-GraphQl and Typegoose, I aim to streamline my data definitions by consolidating them into one source for both GraphQL schemas and Mongoose queries. Is it feasible to merge the two libraries in a way that allows me to describe bo ...

What is the best way to pass a specific property from a parent component to a child component in Angular when a button is clicked?

Hey there, I'm looking for a way to pass a single property (groupId) from a parent component to a child component. In this case, my child component is using ngx-bootstrap modal. Is there a solution available for this scenario? Essentially, I need to i ...

Handling Click and Mouse Events with React [react-sortable-hoc, material-ui, react-virtualized]

I have come across an interesting example that I would like to share with you. Check out this live working example on Stackblitz When the delete button on the red bin icon is pressed, the onClick event handler does not get triggered (sorting happens inst ...

What methods can be employed to enhance the User interface further?

I recently started using typescript and decided to migrate an existing project to it. In my middleware functions, which are located in a separate file, I have the following function: const checkCampgroundOwnership = async ( req: Request, res: Response ...

experiencing an excessive amount of rerenders when trying to utilize the

When I call the contacts function from the main return, everything seems fine. However, I encounter an error at this point: const showContacts = React.useCallback( (data: UsersQueryHookResult) => { if (data) { return ( < ...

Order processing in Angular 2

As a newcomer to Angular, my main focus is on understanding the order in which the files are processed within an application. To the best of my knowledge, the processing order is as follows: First, main.ts is processed where the bootstrap method associ ...

When using the `const { }` syntax, which attribute is made accessible to the external

I am using the ngrx store as a reference by following this example: https://stackblitz.com/edit/angular-multiple-entities-in-same-state?file=src%2Fapp%2Fstate%2Freducers%2Fexample.reducer.ts Within the code in example.reducer.ts, there is this snippet: ...

Angular component unable to access Service provided via Dependency Injection

After diving into an Angular tutorial yesterday (), I reached a point where services came into play. The Service class, named MediaServiceService and housed in the media-service.service.ts file, had the following structure: import { Injectable } from &ap ...