1 year ago

#384283

test-img

Дмитрий

Don't work deleting coin because old value in setInterval method react hooks

I want delete value in removeCurrency method. The value is being deleted but after 2-3 seconds value is returned. This is hapenning when fetchData method is start. In method fetchData value cryptoCurrency is old.

export function Crypto(props: CryptoProps){
    const [cryptoCurriensies, setCryptoCurriensies] = useState<Coin[]>([ {usd: null, name: 'LUNA'}, {usd: null, name: 'BNB'}, {usd: null, name: 'XRP'}]);
    const [error, setError] = useState('');
    const [intervalId, setIntervalId] = useState<number| undefined>(undefined)

   async function removeCurrency(cryptoName: string){
        let coins = [...cryptoCurriensies];
        let filteredCoins = coins.filter(coin => coin.name !== cryptoName)
        setCryptoCurriensies(filteredCoins);
    }

     useEffect(() => {
         fetchData();
        let intervalId = window.setInterval(() => fetchData(), 5000);
        return () => {
            window.clearInterval(intervalId);
        }
    }
    , [cryptoCurriensies]);

     async function fetchData() {
        try {
            const coins = await Promise.all(
                cryptoCurriensies.map(async (coin) => {
                const res = await fetch(`https://min-api.cryptocompare.com/data/price?fsym=${coin.name}&tsyms=USD&api_key=${API_KEY}`);
                const usd = await res.json();
                let price = Number(usd.USD);
                return { ...coin, usd: price };
              })
            );
            setCryptoCurriensies([...coins])
          } catch (e) {
            console.log(e);
          }
    } 

    function setCrypto(coins: Coin[]){
        setCryptoCurriensies(coins);
    }

    const add = (name: string) => {
        fetch(`https://min-api.cryptocompare.com/data/price?fsym=${name}&tsyms=USD&api_key=${API_KEY}`, { mode: 'cors' })
            .then(res => res.json())
            .then(
                (result) => {
                    if (result.Response === 'Error') {
                        addError(name, result.Message);
                        return;
                    }
                     addNameToState(name);
                },
                (error) => {
                    addError(name, error);
                }
            )
    }

    function addNameToState(name: string) {
        let coins = [...cryptoCurriensies, {name: name, usd: null}];
        setCryptoCurriensies(coins);
    }

    function addError(name: string, error: string) {
        setError(`Error occurred: not found crypto with name = ${name} in base ` + error)
    }

    function clearMessage(){
        setError('');
    }

        return <div className="crypto">
            <h1 className="header">CryptoMoney</h1>
            <CryptoList cryptoCurrensies={cryptoCurriensies} removeCurrency={removeCurrency} setCoins={setCrypto}/>
            <CryptoInput add={add} />
            <Modal message={error} title={'Error'} clearMessage={clearMessage} />
        </div>
}
}```

reactjs

react-hooks

closures

0 Answers

Your Answer

Accepted video resources