Reputation: 25
How would I get a randomly generated value in an object array to regenerate each time it is accessed? For example the following code assigns the random value on page load, how would I get it to update each time it's accessed?
const values = [
{ name: "john", favouriteColor: getRandomColor() },
{ name: "tom", favouriteColor: colors[5] },
]
{displayColor ? <p>Favourite color is {values[0].favouriteColor}</p> : ""}
<button onClick={toggleDisplayColor}>Favourite Color</button>
Upvotes: 1
Views: 69
Reputation: 35309
You can use a getter on the property. Everytime it's accessed it will return a random color.
const values = [{
name: "john",
get favouriteColor() {return favColor()}
},
{
name: "tom",
favouriteColor: 'white'
},
]
function favColor() {
return `${~~(Math.random()*255)}, ${~~(Math.random()*255)}, ${~~(Math.random()*255)}`
}
document.querySelector("#fav-color").textContent = values[0].favouriteColor;
document.querySelector("#fav-color-2").textContent = values[1].favouriteColor;
<p>Favourite random color is <span id="fav-color"></span></p>
<p>Favourite color is <span id="fav-color-2"></span></p>
Upvotes: 1
Reputation: 397
Try to use a function instead:
function getValues() {
return [
{ name: "john", favouriteColor: getRandomColor() },
{ name: "tom", favouriteColor: colors[5] },
];
}
And your example would be
{displayColor ? <p>Favourite color is {getValues()[0].favouriteColor}</p> : ""}
<button onClick={toggleDisplayColor}>Favourite Color</button>
Upvotes: 1