something similar to useMutation from react-query #550
-
Is there something similar to the useMutation hook from react-query or someway it can be replicated ? Basically what I want is to have loading state while a POST request is happening |
Beta Was this translation helpful? Give feedback.
Replies: 4 comments 3 replies
-
You can use use-mutation, it will give you a similar API and is not dependent of RQ or SWR |
Beta Was this translation helpful? Give feedback.
-
@bogdansoare you can also use react basic hooks to wrap on top of Implementation Exampleimport { useCallback } from "react";
import { mutate } from "swr";
function useMutation(muationFn = f => f, options = {}) {
const mutationCallback = useCallback(
async (key, _payload) => {
const {
onSuccess = () => {},
onMutate = () => {},
onError = () => {}
} = options;
onMutate(key, _payload);
try {
const payload = await muationFn(_payload);
await mutate(key, payload, false);
onSuccess(key, payload);
} catch (e) {
onError(e);
}
},
[muationFn, options]
);
return mutationCallback;
}
export default useMutation; Usageimport React from "react";
import useSWR from "swr";
import useMutation from "./useMutation";
function fetcher() {
return Promise.resolve(123);
}
export default function App() {
const { data } = useSWR("key", fetcher, {});
const mutateZero = useMutation();
return (
<div
className="App"
onClick={() => {
mutateZero("key", 0);
}}
>
<h1>Data: {data}</h1>
</div>
);
} |
Beta Was this translation helpful? Give feedback.
-
Recently I used graphql-codegen-plugin-typescript-swr and saw it uses graphql-request under the hood! |
Beta Was this translation helpful? Give feedback.
-
can someone provide an example of a custom useMutation hook in swr along with the type support with typescript? |
Beta Was this translation helpful? Give feedback.
You can use use-mutation, it will give you a similar API and is not dependent of RQ or SWR