const ToggleActive = (props: { id: string; activeFlag: boolean }) => {
const ctx = api.useContext();
const {
register,
handleSubmit,
formState: { errors, isSubmitting: isPosting },
} = useForm<formDataType>({
resolver: zodResolver(Flag),
});
const { mutate } = api.users.toggleActive.useMutation({
onSuccess: async () => {
await ctx.users.getById.invalidate();
},
onError: (e) => {
const errorMessage = e.data?.zodError?.fieldErrors;
if (errorMessage && errorMessage[0]) {
//TODO: Find a better way to get the error messages, consider using the toast
console.log(errorMessage);
}
},
});
const onSubmit: SubmitHandler<formDataType> = () => {
//* Flip the boolean
const flippedFlag = !props.activeFlag;
mutate({ id: props.id, activeFlag: flippedFlag });
};
return (
<form className="py-4" onSubmit={onPromise(handleSubmit(onSubmit))}>
<button
value={String(props.activeFlag)}
className="w-full rounded border border-black bg-blue-200"
type="submit"
disabled={isPosting}
{...register("activeFlag")}
>
{props.activeFlag !== true && "Reactivate "}
{props.activeFlag === true && "Deactivate "}
</button>
<span>{errors.activeFlag?.message}</span>
</form>
);
};