Home > Mobile >  How can I accumulate string values ​in useState as an array value in React?
How can I accumulate string values ​in useState as an array value in React?

Time:08-25

I created a value called degrowth LengthImg with the useState array. When the deleteImgfunc function is executed, the value is entered as a string value. if deleteImgfunc excuted The first may contain a "buger" value, if deleteImgfunc excuted second time "pizza" value may come in.

At this time, I want to store string values ​​in degrowthLengthImg as an array.

like this expected answer

    degrowthLengthImg = ["buger", "pizza"]

so i made my code but it comes out like blow

   degrowthLengthImg = ["b", "g", ....]

this is my code

    const [degrowthLengthImg, setDegrowthLengthImg] = useState([])

    const deleteImgfunc = useCallback((value: string) => {
            setDegrowthLengthImg([...degrowthLengthImg, value]);

    }, []);

 return(
     <Pressable style={farmDiaryViewWrapperStyle.imgcloseBtn}
     onPress={() => 
    deleteImgfunc?.(v?.name)}
    >
      )

How can i fix my code?

CodePudding user response:

Use the following to add value to the array. Do not use the push function to push to an array. Also, the useCallback is unnecessary.

    const [degrowthLengthImg, setDegrowthLengthImg] = useState([])

    const deleteImgfunc = useCallback((value: string) => {
           // If you want to add to array
            setDegrowthLengthImg(deg => [...deg, value]);
    }, []);

CodePudding user response:

You should use setDegrowthLengthImg as,

 setDegrowthLengthImg(degrowthLengthImg => [...degrowthLengthImg, value]);
  • Related