-
Hi 👋 I've come across multiple use-cases for accessing the mutation state, much like the state of the regular import * as React from "react";
import useIsMounted from "@/services/useIsMounted";
type MutationRes<T, E extends Error> = {
data: T | null;
error: E | null;
fetching: boolean;
};
export default function useMutation<T, I, E extends Error = Error>(
fn: (input: I) => Promise<T>,
): [MutationRes<T, E>, (input: I) => Promise<T>] {
const isMounted = useIsMounted();
const [state, setState] = React.useState<MutationRes<T, E>>({
data: null,
error: null,
fetching: false,
});
const cb = React.useCallback(
async (input: I) => {
setState({ data: null, error: null, fetching: true });
try {
const data = await fn(input);
if (isMounted()) {
setState({ data, error: null, fetching: false });
}
return data;
} catch (error) {
if (isMounted()) {
setState({ data: null, error: error as E, fetching: false });
}
return Promise.reject(error);
}
},
[fn, isMounted],
);
return [state, cb];
} you can then use it in your mutations, like so: import * as React from "react";
import { useSWRConfig } from "swr";
import fetcher from "@/services/fetcher";
import type { ProgramIndexData, ProgramIndexResponse } from "@/api/program";
import useMutation from "@/services/useMutation";
export default function useActivateProgram() {
const { mutate } = useSWRConfig();
return useMutation(
React.useCallback(
(program: ProgramIndexData) => {
return mutate<ProgramIndexResponse>(`/api/program/?slug=${program.slug}`, async () => {
await fetcher(`/api/program/${program.id}/enroll`, {
method: "POST",
});
return {
program: {
...program,
isEnrolled: true,
},
};
});
},
[mutate],
),
);
} now you can access the mutation state in components where you call it: // ...
const [res, enrollProgram] = useEnrollProgram();
// ... this is especially useful for accessing the Is there some existing native API that I am missing? I've been checking https://swr.vercel.app/docs/mutation Is there maybe a plan for simplifying working with mutations? I'd like to not have to use my own solution like this. Thanks |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
Hey! Have you seen the upcoming useSWRMutation hook in 2.0 beta? Would love to here your feedback! |
Beta Was this translation helpful? Give feedback.
Hey! Have you seen the upcoming useSWRMutation hook in 2.0 beta? Would love to here your feedback!
https://github.com/vercel/swr/releases/tag/2.0.0-beta.0