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 put the value of the array object using useState when rendering for the first time in Reactnative?

I have an object array called targetFarm, and when I run the map function, the value comes out like this.

targetFarm.children.map((item) => item.children.map((v) => console.log("v:", v)));

v = {
    name: "coffee"
}

v = {
    name: "tea"
}

v= {
    name: "icecream"
}

What I want to do is put the value of this v.name in an array form using useState in the box constant. as below

box = [
    "coffee",
    "tea",
    "icecream",
]

But when I used my code
This error pops up.

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

"Cannot read property ‘push’ of undefined"

const [box, setBox] = useState(

    targetFarm.children.map((item) => {
        item.children.map((v) => {
            box.push(v.name)
        })
    })
)

then How can i fix my code?

>Solution :

What I want to do is put the value of this v.name in an array form using useState in the box constant

You can use map and flatMap like below

targetFarm.children.flatMap((item) => item.children.map((v) => v.name);

"Cannot read property ‘push’ of undefined"

From your code, box has not been initialized yet, so undefined does not have push method. That’s why it’s throwing that error.

If you want to assign the default state value for box, you can check the below example.

const [box, setBox] = useState(
    targetFarm.children.flatMap((item) => 
        item.children.map((v) => v.name)
    )
)
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