fix: streamline tag management in TypeTag component by removing unnecessary useEffect hooks

This commit is contained in:
faisolavolut 2025-02-28 15:29:33 +07:00
parent e02bb57422
commit ea4af5e09c
1 changed files with 10 additions and 15 deletions

View File

@ -1,5 +1,4 @@
import { useEffect, useRef, useState } from "react"; import { useRef, useState } from "react";
import get from "lodash.get";
export const TypeTag: React.FC<any> = ({ export const TypeTag: React.FC<any> = ({
name, name,
@ -11,24 +10,12 @@ export const TypeTag: React.FC<any> = ({
field, field,
onChange, onChange,
}) => { }) => {
const [tags, setTags] = useState<string[]>([]); const [tags, setTags] = useState<string[]>(fm.data?.[name] || []);
const [inputValue, setInputValue] = useState(""); const [inputValue, setInputValue] = useState("");
const [editingIndex, setEditingIndex] = useState<number | null>(null); // Index tag yang sedang diedit const [editingIndex, setEditingIndex] = useState<number | null>(null); // Index tag yang sedang diedit
const [tempValue, setTempValue] = useState<string>(""); // Nilai sementara untuk pengeditan const [tempValue, setTempValue] = useState<string>(""); // Nilai sementara untuk pengeditan
const tagRefs = useRef<(HTMLDivElement | null)[]>([]); const tagRefs = useRef<(HTMLDivElement | null)[]>([]);
const val = fm?.data?.[name]; const val = fm?.data?.[name];
useEffect(() => {
if (get(fm, `data.[${name}].length`)) {
setTags(fm.data?.[name]);
}
}, [val]);
useEffect(() => {
fm.data[name] = tags;
fm.render();
if (typeof onChange === "function") {
onChange(tags);
}
}, [inputValue]);
const handleSaveEdit = (index: number) => { const handleSaveEdit = (index: number) => {
if (!disabled) return; if (!disabled) return;
const updatedTags = [...tags]; const updatedTags = [...tags];
@ -36,6 +23,9 @@ export const TypeTag: React.FC<any> = ({
setTags(updatedTags); setTags(updatedTags);
setEditingIndex(null); // Keluar dari mode edit setEditingIndex(null); // Keluar dari mode edit
setTempValue(""); // Reset nilai sementara setTempValue(""); // Reset nilai sementara
fm.data[name] = updatedTags;
fm.render();
if (typeof onChange === "function") { if (typeof onChange === "function") {
onChange(tags); onChange(tags);
} }
@ -51,6 +41,11 @@ export const TypeTag: React.FC<any> = ({
e.stopPropagation(); e.stopPropagation();
setTags([...tags, inputValue]); setTags([...tags, inputValue]);
setInputValue(""); setInputValue("");
fm.data[name] = [...tags, inputValue];
fm.render();
if (typeof onChange === "function") {
onChange(tags);
}
} else if (e.key === "Backspace" && !inputValue && tags.length > 0) { } else if (e.key === "Backspace" && !inputValue && tags.length > 0) {
setTags(tags.slice(0, -1)); setTags(tags.slice(0, -1));
} }