Reputation: 49
first of all sry for my bad english.
I am currently making an application to organize tournaments. I have a ListTournament component that shows the components depending on the sport (prop.sport). What I'm doing is an axios call at the moment the component is created, doing this produces an infinite loop, which I solve by updating the state only if a new sport is selected to the previous one.
Is this the correct way?
import React,{useEffect,useState} from "react";
import Tournament from "./Card";
import "../resources/styles/grid.css";
const axios = require("axios").default;
var selected_sport = ''
export default function ListTournaments(props) {
const [tournaments,setTournaments] = useState([])
const getTournaments = sport => {
axios
.get("https://futbol-back.herokuapp.com/tournaments/sport/" + sport)
.then(function(response) {
// handle success
// tournaments = response.data;
if (props.sport!= selected_sport){ // This is where I correct the infinite loop
console.log(selected_sport)
selected_sport = props.sport
setTournaments(response.data)
}
})
.catch(function(error) {
// handle error
console.log(error);
})
.then(function() {
// always executed
});
};
getTournaments(props.sport)
return (
<div className="tournamentsWrapper">
{tournaments.map((tournament, index) => (
<Tournament
title={tournament.title}
description={tournament.description}
requierements={tournament.requierements}
date={tournament.date}
img={tournament.img}
key={index}
/>
))}
</div>
);
}
Upvotes: 0
Views: 56
Reputation: 1864
It's better to make api call only once the component get mounted:
useEffect(() => {
getTournaments(props.sport)
}, [props.sport]}
Upvotes: 1
Reputation: 3505
You're almost there, you're doing the correct use of the useState hook, but you need to wrap your function in an useEffect hook, because you're. performing a side effect.
useEffect(() => {
const getTournaments = async (sport) => {
axios
.get("https://futbol-back.herokuapp.com/tournaments/sport/" + sport)
.then(function(response) {
// handle success
// tournaments = response.data;
if (props.sport!= selected_sport){ // This is where I correct the infinite loop
console.log(selected_sport)
selected_sport = props.sport
setTournaments(response.data)
}
})
.catch(function(error) {
// handle error
console.log(error);
})
.then(function() {
// always executed
});
};
getTournaments(props.sport);
}, []);
This will assure that your effect will run when the component mounts and it will only run once. All your side effects should go in the use effect
Upvotes: 2