data가 없는 경우 (수정모드가 아닌 신규 등록인 경우) 라디오 버튼 중 “active” 버튼을 디폴트로 활성화시키려고 한다.
const FaqRegistForm = forwardRef(({ data, lang, readOnly = false }, ref) => {
const methods = useForm({
mode: "onChange",
defaultValues: {
title: "",
sort: null,
category: "",
status: "active",
content: "",
publishDate: null,
},
});
const { register, setValue, getValues, reset, watch, control } = methods;
const editorRef1 = useRef();
const [categoryList, setCategoryList] = useState([]);
useEffect(() => {
if (data && categoryList.length > 0) {
const matched = categoryList.find(item => item.value === data.category);
reset({
title: data.title || "",
sort: data.sort || null,
category: matched?.code || "",
status: data.useYn === "Y" ? "active" : "inactive",
content: data.content || "",
publishDate: data.publishDate ? new Date(data.publishDate) : null,
});
}
}, [data, categoryList, reset]);
하이라이트 한 부분을 참고하면, data가 없는 경우 , 즉 빈 객체인 경우 truthy로 통과된다.
키가 있는지 (객체에 내용이 있는지) 를 판단하면 보다 엄격하게 검사할 수 있다.
if (data && Object.keys(data).length > 0 && categoryList.length > 0) {
...