I am using a websocket in my React app. It is an app that displays information from coinbase to the screen. I am trying to make it so that when the user changes the currency, my state only pulls in the information that has a product_id with that currency. So what happens is when I first select a currency, it works perfectly fine, I start only getting data with that currency. But when I then change the state of the currency, I starts giving me data with the newly selected currency, but also the ones that were selected before. I'm new to using websockets so maybe I'm missing something there.
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;