T
TanStack3y ago
vicious-gold

useMutation with action in React Router v6

Is there any way to useMutation with action in React Router v6?
4 Replies
rival-black
rival-black3y ago
You wouldn't be able to use a useMutation react hook in a loader, since that would escape the boundaries of React. In the loader, you could perform your actions (api calls, or others.) and set the data as a result of a mutation or query in react-query using the defined queryClient. They have done something similar here, with a query (https://codesandbox.io/s/github/tanstack/query/tree/main/examples/react/react-router?from-embed=&file=/src/routes/root.jsx). Could I ask why you'd want to access a mutation in a loader? Since mutations are generally user-driven based on an event (hover, click, submit, etc.), not when loading a page.
CodeSandbox
@tanstack/query-example-react-router - CodeSandbox
@tanstack/query-example-react-router using @tanstack/react-query, @tanstack/react-query-devtools, localforage, match-sorter, react, react-dom, react-router-dom, rooks, sort-by
vicious-gold
vicious-goldOP3y ago
Thanks for your answer. Yes, I have a page with a form that mixes UI and mutation code. I just wanna separate them and leverage the useMutation of react-query. I found out that react-router action is a very interesting feature that helps me archive that. But it seems I can't use a hook in the react-router action
extended-salmon
extended-salmon3y ago
React Query meets React Router
React Query and React Router are a match made in heaven.
other-emerald
other-emerald3y ago
Dominik 🇺🇦 (@TkDodo)
@tometo_dev If you use actions, just make a request in there without TanStack Query. If you need a feature of mutations, don't use actions.
Twitter

Did you find this page helpful?