refactored keypairListComponent value getters

This commit is contained in:
Lucas Oliveira 2024-06-17 21:51:23 -03:00
commit 790648dd26

View file

@ -1,7 +1,7 @@
import { useEffect, useRef } from "react";
import { useEffect, useRef, useState } from "react";
import { KeyPairListComponentType } from "../../types/components";
import _ from "lodash";
import { cloneDeep } from "lodash-es";
import { classNames } from "../../utils/utils";
import IconComponent from "../genericIconComponent";
import { Input } from "../ui/input";
@ -20,42 +20,36 @@ export default function KeypairListComponent({
}
}, [disabled]);
const checkValueType = (value) => {
return Array.isArray(value) ? value : [value];
};
const ref = useRef<any>([]);
ref.current =
!value || value?.length === 0 ? [{ "": "" }] : checkValueType(value);
useEffect(() => {
if (JSON.stringify(value) !== JSON.stringify(ref.current)) {
ref.current = value;
onChange(value);
}
}, [value]);
const myValue = Array.isArray(value) ? value : [value];
const handleChangeKey = (event, idx) => {
const oldKey = Object.keys(ref.current[idx])[0];
const updatedObj = { [event.target.value]: ref.current[idx][oldKey] };
ref.current[idx] = updatedObj;
onChange(ref.current);
const oldKey = Object.keys(myValue[idx])[0];
const updatedObj = { [event.target.value]: myValue[idx][oldKey] };
const newValue = cloneDeep(myValue);
newValue[idx] = updatedObj;
onChange(newValue);
};
const handleChangeValue = (newValue, idx) => {
const key = Object.keys(ref.current[idx])[0];
ref.current[idx][key] = newValue;
onChange(ref.current);
const handleChangeValue = (event, idx) => {
const key = Object.keys(myValue[idx])[0];
const updatedObj = { [key]: event.target.value };
const newValue = cloneDeep(myValue);
newValue[idx] = updatedObj;
onChange(newValue);
};
return (
<div
className={classNames(
ref.current?.length > 1 && editNode ? "mx-2 my-1" : "",
myValue?.length > 1 && editNode ? "mx-2 my-1" : "",
"flex h-full flex-col gap-3",
)}
>
{ref.current?.map((obj, index) => {
{myValue?.map((obj, index) => {
return Object.keys(obj).map((key, idx) => {
return (
<div key={idx} className="flex w-full gap-2">
@ -90,16 +84,14 @@ export default function KeypairListComponent({
value={obj[key]}
className={editNode ? "input-edit-node" : ""}
placeholder="Type a value..."
onChange={(event) =>
handleChangeValue(event.target.value, index)
}
onChange={(event) => handleChangeValue(event, index)}
/>
{isList && index === ref.current.length - 1 ? (
{isList && index === myValue.length - 1 ? (
<button
disabled={disabled}
onClick={() => {
let newInputList = _.cloneDeep(ref.current);
let newInputList = cloneDeep(myValue);
newInputList.push({ "": "" });
onChange(newInputList);
}}
@ -122,7 +114,7 @@ export default function KeypairListComponent({
) : isList ? (
<button
onClick={() => {
let newInputList = _.cloneDeep(ref.current);
let newInputList = cloneDeep(myValue);
newInputList.splice(index, 1);
onChange(newInputList);
}}