Skip to content

Saleor Core: the high performance, composable, headless commerce API.

Add dialog error support hook

dominik-zeglen705ac0650f1d
diff --git a/saleor/static/dashboard-next/hooks/useModalDialogErrors/index.ts b/saleor/static/dashboard-next/hooks/useModalDialogErrors/index.ts
new file mode 100644
index 0000000000..0fd055b5fb
--- /dev/null
+++ b/saleor/static/dashboard-next/hooks/useModalDialogErrors/index.ts
@@ -0,0 +1,2 @@
+export { default } from "./useModalDialogErrors";
+export * from "./useModalDialogErrors";
diff --git a/saleor/static/dashboard-next/hooks/useModalDialogErrors/useModalDialogErrors.test.ts b/saleor/static/dashboard-next/hooks/useModalDialogErrors/useModalDialogErrors.test.ts
new file mode 100644
index 0000000000..e61aafc0cb
--- /dev/null
+++ b/saleor/static/dashboard-next/hooks/useModalDialogErrors/useModalDialogErrors.test.ts
@@ -0,0 +1,44 @@
+import { renderHook } from "@testing-library/react-hooks";
+
+import useModalDialogErrors from "./useModalDialogErrors";
+
+const errors = ["err1", "err2"];
+
+test("Does not render errors after close", () => {
+ const { result, rerender } = renderHook(
+ ({ errors, open }) => useModalDialogErrors(errors, open),
+ {
+ initialProps: {
+ errors: [] as string[],
+ open: false
+ }
+ }
+ );
+
+ // Open modal
+ rerender({
+ errors: [],
+ open: true
+ });
+ expect(result.current.length).toBe(0);
+
+ // Throw errors
+ rerender({
+ errors,
+ open: true
+ });
+ expect(result.current.length).toBe(2);
+
+ // Close modal
+ rerender({
+ errors,
+ open: false
+ });
+
+ // Open modal
+ rerender({
+ errors,
+ open: true
+ });
+ expect(result.current.length).toBe(0);
+});
diff --git a/saleor/static/dashboard-next/hooks/useModalDialogErrors/useModalDialogErrors.ts b/saleor/static/dashboard-next/hooks/useModalDialogErrors/useModalDialogErrors.ts
new file mode 100644
index 0000000000..0cb30c870b
--- /dev/null
+++ b/saleor/static/dashboard-next/hooks/useModalDialogErrors/useModalDialogErrors.ts
@@ -0,0 +1,22 @@
+import { useState } from "react";
+
+import useStateFromProps from "../useStateFromProps";
+
+function useModalDialogErrors<TError>(
+ errors: TError[],
+ open: boolean
+): TError[] {
+ const [state, setState] = useStateFromProps(errors);
+ const [prevOpenState, setPrevOpenstate] = useState(open);
+
+ if (open !== prevOpenState) {
+ setPrevOpenstate(open);
+ if (!open) {
+ setState([]);
+ }
+ }
+
+ return state;
+}
+
+export default useModalDialogErrors;