Почему возникает проблема при использовании API?

Всем привет! Создаю проект на React, с использованием фреймворка Next.js. В проекте используется API, запросы к которому отправляются при помощи axios.
Вот код отправки запроса API:
В index.js создаю элемент :

<API
    width={isMobile ? '40%' : '17%'}
    className={styles.maxwidth} type={isMobile ? '' : '2'}
    columns={isMobile ? ['название', 'цена', 'изменение'] : ['название', 'символ', 'цена', 'капитализ.', 'курс']}
    template={isMobile ? [
        ['Bitcoin', '???', '?? %']
    ]
    : [
        ['Bitcoin', '???', '?? $', '?? $', '?? %']
    ]}
    func={fetchCryptoRating}
    isMobile={isMobile}
/>

Затем в файле components/API.jsx произвожу некоторые действия, а именно задаю промежуток отправки API:

import React, {useState, useEffect} from 'react'
import Table from '../components/Table.jsx'

const API = ({ columns, template, width = 'auto', type = '', className = '', fake, func, isMobile }) => {
    const [tables, setTables] = useState(template);
    const [prices, setPrices] = useState(false);
    const [color, setColor] = useState(false);
    useEffect(() => {
        setTimeout(() => {
            func(setTables, setPrices, setColor, prices, isMobile)
            console.log(color)
        }, 10000)
    })

    return (
        <Table
            width={width}
            className={className}
            columns={columns}
            tables={tables}
            type={type}
            fake={fake}
            colors={color}
        />
    )
}

export default API;

И потом запускаю функцию, которую передал в элемент :

import { cryptoList, cryptoName } from './Data'
import axios from 'axios'

export async function fetchCryptoRating(setTables, setPrices, setColor, prices, isMobile) {
    const tables = []
    const priceData = []
    const colors = []
    const options = {
        method: 'GET',
        url: 'https://binance43.p.rapidapi.com/ticker/24hr',
        headers: {
          'X-RapidAPI-Host': 'binance43.p.rapidapi.com',
          'X-RapidAPI-Key': '5d54ff98ecmsh76d7bb813122478p16a6edjsnbd7442cf7856'
        }
    };
    const result = await axios.request(options)
    var serverData = result.data.filter(item => cryptoList.indexOf(item.symbol) != -1)
    var count = 0
    serverData.forEach(item => {
        if (prices) {
            if (parseInt(item.lastPrice) > prices[count]) {
                colors.push('#23C14F')
            }
            if (parseInt(item.lastPrice) < prices[count]) {
                colors.push('#FF4545')
            }
            if (parseInt(item.lastPrice) == prices[count]) {
                colors.push('#433532')
            }
        }
        else {
            colors.push('#433532')
        }
        const itemData = isMobile ? [
            cryptoName[count],
            `${parseInt(item.lastPrice)} $`,
            `${parseFloat(item.priceChangePercent).toFixed(2)} %`
        ] : [
            cryptoName[count],
            cryptoList[count].slice(0, 3),
            `${parseInt(item.lastPrice)} $`,
            `${parseInt(item.lastPrice) * 19200000} $`,
            `${parseFloat(item.priceChangePercent).toFixed(2)} %`
        ]
        tables.push(itemData)
        priceData.push(parseInt(item.lastPrice))
        count ++
    })
    setTables(tables)
    setPrices(priceData)
    setColor(colors)
}

Мое недоумение в том, что строчка console.log(color) в файле компонента с каждым разом выводит все больше строк:
После первого запроса:
['#433532', '#433532']
После второго запроса:
['#433532', '#433532']
['#433532', '#433532']
['#433532', '#433532']
['#433532', '#433532']
['#433532', '#433532']
['#433532', '#433532']
И с каждым запросом все больше. Хотя каждый раз отправляю только один запрос. Кто может объяснить, почему так происходит. Если что-то не понятно в моем объяснении, могу более подробно разъяснить. Буду очень благодарен за ответ
  • Вопрос задан
  • 119 просмотров
Решения вопроса 1
@Che603000
c 2011 javascript
useEffect(() => {
        setTimeout(() => {
            func(setTables, setPrices, setColor, prices, isMobile)
            console.log(color)
        }, 10000)
    },[]);  // без [] useEffect будет вызываться при каждом рендеринге
Ответ написан
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы