Estoy usando un websocket en mi aplicación React. Es una aplicación que muestra información de coinbase a la pantalla. Estoy tratando de hacer que cuando el usuario cambie la moneda, mi estado solo extraiga la información que tiene un product_id con esa moneda. Entonces, lo que sucede es que cuando selecciono una moneda por primera vez, funciona perfectamente bien, solo empiezo a obtener datos con esa moneda. Pero cuando luego cambio el estado de la moneda, me comienzan a dar datos con la moneda recién seleccionada, pero también con las que se seleccionaron antes. Soy nuevo en el uso de websockets, así que tal vez me estoy perdiendo algo allí.
import React, { useState, useEffect } from "react"; import Chart from "./components/Chart"; import DropDown from "./components/DropDown"; function App() { const [bestBid, setBestBid] = useState({price: null, size: null}) const [bestAsk, setBestAsk] = useState({price: null, size: null}) const [bidChartData, setBidChartData] = useState() const [displayBidChartData, setDisplayBidChartData] = useState([]) const [currency, setCurrency] = useState() const ws = new WebSocket("wss://ws-feed.exchange.coinbase.com"); const apiCall = { type: "subscribe", product_ids: [ "ETH-USD", "BTC-USD", "LTC-USD", "BCH-USD" ], channels: ["level2"] }; ws.onopen = (event) => { ws.send(JSON.stringify(apiCall)); }; ws.onmessage = function (event) { const json = JSON.parse(event.data); if(json.type === 'l2update'){ (json.product_id === currency && console.log(json)) } /* if(json.type === 'l2update' && json.product_id === currency){ const newInfo={price: json.changes[0][1], size: json.changes[0][2]} if(json.changes[0][0] === 'buy'){ setBestBid(newInfo) } //newChartData = {bidPoint: json.bids[0][0], askPoint: json.asks[0][0]} };*/ } function changeCurrency(selection) { setCurrency(selection) } return ( <div> <DropDown changeCurrency={changeCurrency} /> <h3>Best Bid</h3> <h6>Bid Price</h6> {bestBid.price} <h6>Bid Size</h6> {bestBid.size} <h3>Best Ask</h3> <h6>Ask Price</h6> {} <h6>Ask Size</h6> {} {currency} </div> ); } export default App;