Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

    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?

>Solution :

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]);
    }, []);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading