I have an array object called growthLengthImg and ecdysisInfoImg. I also have states called upgrowthLengthImg, upecdysisInfoImg, degrowthLengthImg, and deecdysisInfoImg.
When updateFlag becomes true, I extracted the values of growthLengthImg and ecdysisInfoImg and put the values in the state using setUpgrowthLengthImg and setUpecdysisInfoImg.
At this time, when I execute deleteImgfunc1 or deleteImgfunc2 function, I extract the value of restImg, put it in the value of setUpgrowthLengthImg, and use setDegrowthLengthImg to save v.name.
But I think having two deleteImgfunc seems inefficient. This is because deleteImgfunc may increase further. So I want to merge deleteImgfunc into one and remove duplicates, but how do I do that?
this is my code
growthLengthImg = [
{
byteSize: 20089,
extension: "jpeg",
name: "tes",
originName: "growthLength 1",
}
]
ecdysisInfoImg = [
{
byteSize: 20086,
extension: "jpeg",
name: "asd",
originName: "ecdysisInfo 2" ,
}
]
const [upgrowthLengthImg, setUpgrowthLengthImg] = useState([])
const [upecdysisInfoImg, setUpecdysisInfoImg] = useState([])
const [degrowthLengthImg, setDegrowthLengthImg] = useState([])
const [deecdysisInfoImg, setDeecdysisInfoImg] = useState([])
useEffect(() => {
if (updateFlag) {
const growthLengthImg = Images.filter((v: ImagesInfo) => v.originName.includes("growthLength"));
const ecdysisInfoImg = Images.filter((v: ImagesInfo) => v.originName.includes("ecdysisInfo"));
setUpgrowthLengthImg(growthLengthImg)
setUpecdysisInfoImg(ecdysisInfoImg)
}
}, [updateFlag]);
const deleteImgfunc1 = (value: string) => {
//value : "tes"
const restImg = upgrowthLengthImg.filter((v) => !v?.name.includes(value));
setUpgrowthLengthImg([])
setUpgrowthLengthImg(restImg);
setDegrowthLengthImg([...degrowthLengthImg, value]);
}
const deleteImgfunc2 = (value: string) => {
const restImg = upecdysisInfoImg.filter((v) => !v?.name.includes(value));
setUpecdysisInfoImg([])
setUpecdysisInfoImg(restImg);
setDeecdysisInfoImg([...deecdysisInfoImg, value]);
}
return (
<>
<Pressable
onPress={() => deleteImgfunc1?.(v?.name)}
>
</Pressable>
<Pressable
onPress={() => deleteImgfunc2?.(v?.name)}
>
</Pressable>
</>
)
CodePudding user response:
Make a generic func called deleteImage and passs type as param, hope it helps, feel free for doubts
const deleteImgfunc = (value: string, type:string) => {
if(type === "first_type"){
const restImg = upgrowthLengthImg.filter((v) => !v?.name.includes(value));
setUpgrowthLengthImg([])
setUpgrowthLengthImg(restImg);
setDegrowthLengthImg([...degrowthLengthImg, value]);
}
if(type === "second_type"){
const restImg = upecdysisInfoImg.filter((v) => !v?.name.includes(value));
setUpecdysisInfoImg([])
setUpecdysisInfoImg(restImg);
setDeecdysisInfoImg([...deecdysisInfoImg, value]);
}
}
and you can do onPress like this
<Pressable
onPress={() => deleteImgfunc?.(v?.name,"first_type")}
>
</Pressable>
<Pressable
onPress={() => deleteImgfunc?.(v?.name,"second_type")}
>
</Pressable>