0

When I do this It works

import React, { useState, useEffect } from 'react'

// Node Binance API
// https://github.com/binance-exchange/node-binance-api

const Binance = require('node-binance-api')
const binance = new Binance().options({
  APIKEY: 'xxxxxxxxxx',
  APISECRET: 'xxxxxxxxxx'
})

// BTCUSDT - price
const FuturesPrices = () => {

  const [btcPrice, setBtcPrice] = useState([])

    useEffect(() => {

      async function fetchMyAPI() {

        let response = await binance.futuresPrices()

        response = response.BTCUSDT

        setBtcPrice(response)

        //console.log(response)
      }

      fetchMyAPI()

    }, [btcPrice])

    return <div>{btcPrice}</div>

}

export default FuturesPrices

But when I try example down below It doesn't work. Gives "error Unhandled Rejection (Error): ws does not work in the browser. Browser clients must use the native WebSocket object"

import React, { useState, useEffect } from 'react'

// Node Binance API
// https://github.com/binance-exchange/node-binance-api

const Binance = require('node-binance-api')
const binance = new Binance().options({
  APIKEY: 'xxxxxxxxxx',
  APISECRET: 'xxxxxxxxxx'
})

// BTCUSDT - price
const BtcPriceTicker = () => {

  const [btcPriceTicker, setBtcPriceTicker] = useState([])

    useEffect(() => {

      async function fetchMyAPI() {

        let response = await binance.futuresMiniTickerStream( 'BTCUSDT' )

        response = response.close

        setBtcPriceTicker(response)

        //console.log(response)
      }

      fetchMyAPI()

    }, [btcPriceTicker])

    return <div>{btcPriceTicker}</div>

}

export default BtcPriceTicker;

My GitHub https://github.com/React-Binance/react-binance-api Contribute to React-Binance/functional components development

Reaction
  • 3
  • 6
  • Other than the effect not [cleaning up](https://reactjs.org/docs/hooks-effect.html#effects-with-cleanup) and you trying to dump a JavaScript object in jsx (use `
    {JSON.stringify(btcPrice,undefined,2)}
    ` instead) and your code indentation is off, I don't see a problem with the code. Do you get any errors?
    – HMR Jun 28 '20 at 11:22
  • Thank you for answering. I've rephrased my question. Please take a look. I'm new to react, can you tell me where and how to use cleaning with functional components – Reaction Jun 28 '20 at 12:45

1 Answers1

1

By passing [btcPrice] in the dependency array, you're telling react to run this effect if the value of btcPrice changes.

Form Official docs

You can tell React to skip applying an effect if certain values haven’t changed between re-renders. To do so, pass an array as an optional second argument to useEffect

You can pass an empty array instead, which will make useEffect run only once like componentDidMount

Siddharth
  • 1,200
  • 8
  • 13