RTK Query: Pre-Mutation Hooks #1332
agusterodin
started this conversation in
Ideas
Replies: 1 comment
-
The application lifecycle happens in a middleware as a reaction to actions being dispatched. At that point, there is no option to block/prevent anything anymore. I'd recommend you to just write this as a custom hook: function useMyMutationWithConditions(options){
const [run, result] = useMyMutation(options)
const store = useStore()
const runWithCondition = (args) => {
// do checks, do a return if you don't wan to sart
run(args)
}
return [runWithCondition, result]
} |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
Howdy! I am looking for a way to perform some checks on data in arbitrary parts of the application's state before a mutation is made (before request even sends). I would like to dispatch actions in response to these checks and potentially choose not to send a request at all if conditions aren't met. Ideally this would be doable directly in createApi. onQueryStarted gives us everything we need (getState and dispatch) but doesn't afford the capability to prevent the request from happening.
The simple solution that doesn't involve a "pre-mutation hook" would be to subscribe the component that triggers the request to the entire store and perform the checks inside the component. The problem with this is that I would like to keep business logic separate from the components if at all possible. I also don't want unnecessary subscriptions inside of a component when I really just want to get the state at the exact time a mutation gets triggered.
Another idea that would avoid unnecessary component subscription and allow for business logic to be separated out of the component without the need for a "pre-mutation hook" would be to just create a plain JavaScript function outside of the component (preferably grouped with other business logic) and use store.getState() and store.dispatch() directly by importing the store. The function could return true or false and that would tell the component whether to trigger the mutation or not. This doesn't feel like a clean solution. Also this approach wouldn't make the "pre mutation logic" to be truly global.
To be clear: by "hook" in this, I do not mean a React hook but rather a mutation lifecycle tie-in.
Beta Was this translation helpful? Give feedback.
All reactions