Reputation: 199
Hi :) I'm trying to get an array of numbers from my api that returns me something like: [{"numbers":[9,7,56,58,48,18],"gameId":1},{"numbers":[3,8,10,60,35,5],"gameId":2},{"numbers":[39,24,33,26,48,55],
I'm using axios and everytime I make a request this is what happens: [] length: 0 [[Prototype]]: Array(0)
this is my code:
const[game,setGame]= React.useState([]);
var[myGameNumbers, setMyGameNumbers]=React.useState([]);
React.useEffect(()=>{
axios.get("http://localhost:8080/games/game12").then((response)=>{
setGame(response.data);
});
}, []);
if (!game) return null;
function mappingNumbers(){
game.map((game) => (
setMyGameNumbers==game
));
if(!myGameNumbers) return null; else console.log(myGameNumbers);
}
this is the button that triggers the function:
<a href="#" className="button" onClick={mappingNumbers()}>
<p className="bttn-p">GERAR NÚMEROS</p>
</a>
I'm looking for a way to bring my array numbers, like this: [9,7,56,58,48,18]
everytime I click on the button. If anyone knows how to help I'd be thankful :D
this is my full code if theres anything I've left out: https://github.com/vitoriaacarvalho/jogando-na-mega-sena/tree/main/front/jogando-na-mega
Upvotes: 0
Views: 377
Reputation: 4662
In your mappingNumbers
you map over the game
and do some check ==
against the setMyGameNumbers
function which will not work. The correct syntax will be something like setMyGameNumbers(game)
You also check if myGameNumbers
does not exist but it will always exist since the initial value is an empty array []
this is why the console.log logs an empty array.
...
if (!game) return null;
// will log everytime when a state gets updated
// and if the above statement is false
console.log("myGameNumbers", myGameNumbers);
function mappingNumbers() {
if (game.length < 1) return null;
setMyGameNumbers(game);
}
Updated the onClick
with a correct syntax
<a href="#" className="button" onClick={() => mappingNumbers()}>
<p className="bttn-p">GERAR NÚMEROS</p>
</a>
Upvotes: 2