2
I’m looking to generate 4 random values from an array. I’ve tried using Math.Random, but it’s in an infinite loop...
import React, { useState, useEffect } from "react";
import api from "../../services/api";
export default function Popular() {
const [AllServices, setService] = useState([]);
useEffect(() => {
api.get("/").then((response) => {
setService(response.data);
});
}, []);
return (
<div className="cards">
{AllServices.slice(0, 4).map(service => (
<div className="card" key={service.id}>
<img src={service.imageUrl} alt={service.title} />
<p className="title">{service.title}</p>
<div className="info">
<i className="material-icons">grade</i>
<span className="rating">{service.rating}</span> · {" "}
<span className="category">{service.category}</span>
</div>
</div>
))}
</div>
);
}
@Danizavtz I didn’t understand, could explain me better?
– Jhonata Bonadio
I would like to know the range of the draw of the numbers, are random number from zero to ten?
– Danizavtz
@Danizavtz Ah, yes. From 0 to 8.
– Jhonata Bonadio
Where do you want to use these random values? instead of
.slice(0, 4)
to shorten the array? or want to have an array with random numbers inside? and how many? and 0 to 8?– Sergio
@Sergio Instead of . Slice(), I want to pull 4 random values from the array. It would be 0 to the size of the array, in case 8.
– Jhonata Bonadio
Okay, and with Slice (as in the question) you have an infinite loop as referees or it works well?
– Sergio
@Sergio I managed to solve the infinite loop, now it’s just the question of generating the 4 random values
– Jhonata Bonadio
@Sergio It worked, thank you very much!
– Jhonata Bonadio
Note that this method produces flawed results. I made an answer that serves to get random results, if that is an important requirement.
– Rodrigo Amaral