0

I'm new to React, sorry about this stupid question. I get the error:

Uncaught TypeError: products is not iterable

If I create a separate array (myArray) and pass this to setProducts, this works, but the loop doesn't when calling setProducts on each pass. Is useState() not allowed within a for loop?

const [products, setProducts] = useState([]);

    let myArr = [];
    function selectProducts() {
        for (let i = 0; i < 4; i++) {
            let rand = Math.floor(Math.random() * jsData.length + 1);
            let item = jsData[rand];

            //myArr.push(item);
            setProducts([...products, item]);
        }
        //setProducts(myArr);
        console.log(products);
    }
skyboyer
  • 22,209
  • 7
  • 57
  • 64
Datadump
  • 45
  • 6
  • Calling a state setter is allowed, but you have to keep in mind that the state you just set will not be reflected until the next render. You could also consider using `.map` instead, allowing you to set the state just once, instead of having to deal with stale closures or the callback form of the state setter. – CertainPerformance Nov 19 '21 at 02:33
  • So that link above doesn't exactly tell what's wrong with the spread operator mixed with the for loop. What I understand from your comment is that for each call the setProducts it needs to re-render first before the next iteration and it can't do the setting while looping, it's like one iteration then one one render first. So the solution is to assign all the items in the array and then call the useState once passing the array, is this it? Thanks – Datadump Nov 19 '21 at 03:01
  • Yes, call the state setter just once, ideally. – CertainPerformance Nov 19 '21 at 03:06
  • ok, how about your suggestion to use .map? where do I use that? – Datadump Nov 19 '21 at 03:09
  • Using the mapper function of `Array.from` you can `setProducts(Array.from({ length: 4 }, () => jsData[Math.random() * jsData.length + 1]))` – CertainPerformance Nov 19 '21 at 03:12
  • thanks heaps, will use this. – Datadump Nov 19 '21 at 03:17

0 Answers0