Skip to content

Commit

Permalink
Auto-save for settings modal (#3777)
Browse files Browse the repository at this point in the history
auto-save for settings modal
  • Loading branch information
timarney authored Jun 10, 2024
1 parent 58ab090 commit f986d7d
Showing 1 changed file with 35 additions and 1 deletion.
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
"use client";
import React, { useCallback, useState, useMemo } from "react";
import React, { useCallback, useState, useMemo, useEffect } from "react";
import { useTranslation } from "@i18n/client";
import { useSession } from "next-auth/react";
import { Button } from "@clientComponents/globals";
Expand Down Expand Up @@ -27,6 +27,7 @@ import {

import { toast } from "@formBuilder/components/shared/Toast";
import { ErrorSaving } from "@formBuilder/components/shared/ErrorSaving";
import { useTemplateContext } from "@lib/hooks/form-builder/useTemplateContext";
import { safeJSONParse } from "@lib/utils";

enum DeliveryOption {
Expand All @@ -51,11 +52,15 @@ export const SettingsDialog = ({
const { t, i18n } = useTranslation("form-builder");
const { status, data } = useSession();

const { createOrUpdateTemplate } = useTemplateContext();

/*--------------------------------------------*
* Current store values
*--------------------------------------------*/
const {
id,
getId,
setId,
email,
subjectEn: initialSubjectEn,
subjectFr: initialSubjectFr,
Expand All @@ -72,6 +77,8 @@ export const SettingsDialog = ({
updateField,
} = useTemplateStore((s) => ({
id: s.id,
getId: s.getId,
setId: s.setId,
email: s.deliveryOption?.emailAddress,
subjectEn: s.deliveryOption?.emailSubjectEn,
subjectFr: s.deliveryOption?.emailSubjectFr,
Expand Down Expand Up @@ -134,6 +141,33 @@ export const SettingsDialog = ({
return getBrand(brandName, options);
}, [brandName]);

useEffect(() => {
// Auto save the template when the settings dialog
// is opened if no id exists
const autoSave = async () => {
if (!createOrUpdateTemplate) {
return;
}

const id = getId();
if (id) {
return;
}

const formConfig = safeJSONParse(getSchema());
const { formRecord: template, error } = await createOrUpdateTemplate({ id, formConfig });

if (error) {
toast.error(<ErrorSaving />, "wide");
return;
}

template && setId(template.id);
};
autoSave();
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);

/*--------------------------------------------*
* Delivery options state and handlers
*--------------------------------------------*/
Expand Down

0 comments on commit f986d7d

Please sign in to comment.