E C I N
E C I N

Reputation: 201

Get isLoading state of manually initiated RTK Query mutation

I'm working on a Nextjs project with RTK Query. Can someone tell me how to access the isLoading state of the mutation that is initiated like this https://redux-toolkit.js.org/rtk-query/api/created-api/endpoints#initiate. I don't want to use the generated hook useLoginMutation but instead get the data by unwrapping the returned result after dispatching like this await dispatch(api.endpoints.login.initiate()).unwrap() because I don't want my form to re render. Thank you in advance!

Upvotes: 0

Views: 1247

Answers (1)

phry
phry

Reputation: 44276

because I don't want my form to re render.

Hi, RTK Query author here.

Generally, you can use the selectFromResult option to reduce the amount of fields returned from the hook, and as such also reduce the amount of rerenders (as less things are changing).

Generally though, I have to strongly advise you: don't care about the amount of rerenders on this level. React is made to fastly rerender your components. One, two, or even five rerenders within a 1-3 seconds frame should not make any difference for your application - usually, your component will rerender on every keypress in your form anyways!

If, and only if you are seeing actual performance degradation, you get to the point of optimizing things like this - and then you would see if somewhere you have dozens or hundreds of rerenders, but still do not care about single-digit rerender numbers. If single-digit rerenders are a problem for you, you have heavy computation logic inside your components, and you need to optimize that - the execution of one of your component functions should always be in the sub-milliseconds. Then that's the place to optimize.

As for triggering the mutation with initiate: It will be loading until your await continues and done after that. If you just need that information, there is no need to access an isLoading state. You must set the component state if you need that information in your component. And that would trigger a rerender. You see where I am going: use the hooks! That's what they are made for.

Also, if using initiate: make sure to unsubscribe the result afterward or it will stay in cache forever. Again, this is something the hooks do for you.

Upvotes: 1

Related Questions