Home > Software design >  How can I put the value of the array object using useState when rendering for the first time in Reac
How can I put the value of the array object using useState when rendering for the first time in Reac

Time:07-29

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.

"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?

CodePudding user response:

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)
    )
)
  • Related