I've got a question about useEffect and useState inside of it.
I am building a component:
const [id, setId] = useState(0);
const [currencies, setCurrencies] = useState([]);
...
useEffect(()=> {
const getCurrentCurrency = async () => {
const response = await fetch(`https://api.exchangeratesapi.io/latest?base=GBP`);
const data = await response.json();
const currencyArray = [];
const {EUR:euro ,CHF:franc, USD: dolar} = data.rates;
currencyArray.push(euro, dolar/franc,1/dolar);
console.log("currencyArray", currencyArray);
setCurrencies(currencies => [...currencies, currencyArray]);
}
getCurrentCurrency();
}, [id, currencies.length]);
Which is used for making a new API request when only id change. I need to every time that ID change make a new request with new data. In my case now I have infinite loop. I try to use dependencies but it doesn't work as I expected.
currencies.length1if you only want to update when ID changecurrencies.length) but it doesn't workidcome from?const [id, setId] = useState(0);and then i change it somewhere in the handler for go between the slides in slider like this:const goToPrevSlide = () => { id === 0 ? setId(2) : setId(id-1); } const goToNextSlide = () =>{ id === 2 ? setId(0) : setId(id+1); }