0

I am learning react as beginner , I am trying to create an array of products object. I have created it in a js file. Then exported the array. In another file I have imported and it works. Problem is whenever I refresh the page it gets new random values. As I have use random function to generate the object values. What I want is, after generating the array of objects once, it won't generate randomly further. How can I do that?

export const cosmetics = [];
const names = [];
const prices = [];

//random generated  name list---------------------------------
function set_name() {
    const letters = 'abcdefghijklmnopqrstuvwxyz'
    for (let j = 0; j < 20; j++) {

        let name = '';
        for (let i = 0; i < 4; i++) {
            name += letters.charAt(Math.floor(Math.random() * 26))
        }
        names.push(name)
    }
}
// random generate prices list ---------------------------
function set_price() {
    for (let j = 0; j < 20; j++) {
        prices.push(Math.floor(Math.random() * 500) + 1000)
    }
}
//  create data set array of objects
function construct_data() {
    for (let i = 0; i < 20; i++) {
        const cosmetic = {
            id: i + 1,
            name: names[i],
            price: prices[i]
        }
        cosmetics.push(cosmetic)
    }
}

set_name();
set_price();
construct_data();


  • You would have to save the values somewhere, like a database or maybe browser storage. – Axekan Sep 27 '22 at 13:14
  • Either just generate once and then save the values like Axekan suggested, or take a look at [this thread](https://stackoverflow.com/questions/521295/seeding-the-random-number-generator-in-javascript/19303725#19303725) or [this one](https://www.sololearn.com/Discuss/1469791/solved-seeding-js-math-random) on possible ways to make a seedable prng. – Driftr95 Sep 27 '22 at 13:38
  • You can not do this because `Math.random` is executed on runtime which results in a different output. You could generate your data once, and store the results in a `JSON` file (so-called fixture) – marcobiedermann Sep 28 '22 at 10:27

0 Answers0