Skip to content

Instantly share code, notes, and snippets.

@jide
Created December 5, 2023 16:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jide/3cf4ca1ec896e0b1a039114c3b1f1a17 to your computer and use it in GitHub Desktop.
Save jide/3cf4ca1ec896e0b1a039114c3b1f1a17 to your computer and use it in GitHub Desktop.
Next JS toast actions messages
export async function submitPost(post) {
const { error } = await supabase
.from("posts")
.insert(post);
if (error) {
return error;
}
return 'Success !';
}
"use client";
import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { Form } from "@/components/ui/form";
import { Button } from "@/components/ui/button";
import * as z from "zod";
import { useFormAction } from "@/lib/useFormAction";
export function PostForm() {
const [action, isLoading] = useFormAction(submitPost);
const formSchema = z.object({
// ...your form schema
});
const form = useForm({
resolver: zodResolver(formSchema),
defaultValues: {
// ...your form default values
},
});
const onSubmit = (data) => {
// ...additionnal logic
action(data);
};
return (
<Form {...form}>
<form onSubmit={form.handleSubmit(onSubmit)}>
{/* ... your form */}
<Button type="submit">{isLoading ? "Loading..." : "Submit"}</Button>
</form>
</Form>
);
}
"use client";
import { useEffect, useState } from "react";
import { useToast } from "@/components/ui/use-toast"; // From @shadcn/ui
import useTranslation from "next-translate/useTranslation";
export function useFormAction(action, defaultState = null) {
const { t } = useTranslation("common");
const [isLoading, setIsLoading] = useState(false);
const [message, setMessage] = useState(defaultState);
const { toast } = useToast();
useEffect(() => {
if (message) {
if (typeof message === "string") {
toast({
title: t("Success"),
description: message,
});
} else {
toast({
title: t("Error"),
variant: "destructive",
description: message.message,
...message,
});
}
}
}, [message]);
async function actionWithLoading(...args) {
setIsLoading(true);
const res = await action(...args);
setMessage(res);
setIsLoading(false);
}
return [actionWithLoading, isLoading, message];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment