@fremtind/jkl-feedback-react
Version:
Jøkul react feedback component
82 lines (81 loc) • 2.65 kB
JavaScript
var __defProp = Object.defineProperty;
var __defProps = Object.defineProperties;
var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
var __getOwnPropSymbols = Object.getOwnPropertySymbols;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __propIsEnum = Object.prototype.propertyIsEnumerable;
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
var __spreadValues = (a, b) => {
for (var prop in b || (b = {}))
if (__hasOwnProp.call(b, prop))
__defNormalProp(a, prop, b[prop]);
if (__getOwnPropSymbols)
for (var prop of __getOwnPropSymbols(b)) {
if (__propIsEnum.call(b, prop))
__defNormalProp(a, prop, b[prop]);
}
return a;
};
var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
import {
useState,
useRef,
useCallback,
useEffect
} from "react";
const useMainQuestion = (onSubmit) => {
const [currentValue, setCurrentValue] = useState();
const [message, setMessage] = useState();
const [submitted, setSubmitted] = useState(false);
const feedbackRef = useRef({
onSubmit,
currentValue,
message,
submitted
});
useEffect(() => {
feedbackRef.current = __spreadProps(__spreadValues({}, feedbackRef.current), {
onSubmit,
currentValue,
message,
submitted
});
}, [onSubmit, currentValue, message, submitted]);
const submitHandler = useCallback((intentionalSubmit = true) => {
const { message: message2, currentValue: currentValue2, submitted: submitted2, onSubmit: onSubmit2 } = feedbackRef.current;
if (!submitted2 && currentValue2 !== void 0) {
const feedbackValue = Array.isArray(currentValue2) ? currentValue2.map((option) => option.value) : currentValue2 == null ? void 0 : currentValue2.value;
onSubmit2(__spreadValues({
feedbackValue,
intentionalSubmit
}, intentionalSubmit && message2 ? { message: message2 } : {}));
}
}, []);
const autoSubmit = useCallback(() => submitHandler(false), [submitHandler]);
useEffect(() => {
if (typeof window !== "undefined") {
window.addEventListener("beforeunload", autoSubmit);
}
return () => {
autoSubmit();
window.removeEventListener("beforeunload", autoSubmit);
};
}, [autoSubmit]);
const handleSubmit = (e) => {
e.preventDefault();
submitHandler();
setSubmitted(true);
};
return {
currentValue,
setCurrentValue,
message,
setMessage,
submitted,
handleSubmit
};
};
export {
useMainQuestion
};
//# sourceMappingURL=useMainQuestion.js.map