Home > database >  Only one element is added to the array
Only one element is added to the array

Time:12-11

The code is supposed to add 6 random elements to an array from another array, but for some reason it only adds it once `

  let [cubs, setcubs] = useState([
    {id:1,title:1, img:"https://www.zonkpro.ru/zonk/assets/dice/mini/1.png"},
    {id:2,title:2, img:"https://www.zonkpro.ru/zonk/assets/dice/mini/2.png"},
    {id:3,title:3, img:"https://www.zonkpro.ru/zonk/assets/dice/mini/3.png"},
    {id:4,title:4, img:"https://www.zonkpro.ru/zonk/assets/dice/mini/4.png"},
    {id:5,title:5, img:"https://www.zonkpro.ru/zonk/assets/dice/mini/5.png"},
    {id:6,title:6, img:"https://www.zonkpro.ru/zonk/assets/dice/mini/6.png"},
  ])
  
  let [cubikinapole, setcubikinapole] = useState([

  ])
  
  function sheker(){
    for(let i=0;i<6;i  ){
      let randomcub = Math.floor(Math.random() * (6 - 0)   0)
      let obj = {
        id: new Date().valueOf(),
        title: cubs[randomcub].title,
        img: cubs[randomcub].img
      }
      setcubikinapole([...cubikinapole, obj])
    }
    }

`

Tried the push method but it throws errors

CodePudding user response:

Store the value in temp array until loop is finished and then update the store

function sheker(){
    const list = []
    for(let i=0;i<6;i  ){
      let randomcub = Math.floor(Math.random() * (6 - 0)   0)
      let obj = {
        id: new Date().valueOf(),
        title: cubs[randomcub].title,
        img: cubs[randomcub].img
      }
      list.push(obj)
    }
    
    setcubikinapole(list)

}
  • Related