-
Notifications
You must be signed in to change notification settings - Fork 0
feat: add real-time BTC price ticker #54
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
cmnisal
wants to merge
1
commit into
main
Choose a base branch
from
cmnisal/add-live-bitcoin-price-updates
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+78
−0
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,72 @@ | ||
| "use client"; | ||
|
|
||
| import { useEffect, useRef, useState } from "react"; | ||
| import { motion } from "framer-motion"; | ||
|
|
||
| export default function BtcPriceTicker() { | ||
| const [price, setPrice] = useState<number | null>(null); | ||
| const [prevPrice, setPrevPrice] = useState<number | null>(null); | ||
| const [trend, setTrend] = useState<"up" | "down" | null>(null); | ||
| const priceRef = useRef<number>(0); | ||
| const [rate, setRate] = useState<number | null>(null); | ||
|
|
||
| useEffect(() => { | ||
| const fetchRate = async () => { | ||
| try { | ||
| const res = await fetch("https://open.er-api.com/v6/latest/USD"); | ||
| const data = await res.json(); | ||
| setRate(data.rates.LKR); | ||
| } catch (err) { | ||
| console.error("Failed to fetch LKR rate", err); | ||
| } | ||
| }; | ||
| fetchRate(); | ||
| }, []); | ||
|
|
||
| useEffect(() => { | ||
| if (!rate) return; | ||
| const ws = new WebSocket("wss://ws.coincap.io/prices?assets=bitcoin"); | ||
| ws.onmessage = (event) => { | ||
| const data = JSON.parse(event.data); | ||
| if (data.bitcoin) { | ||
| priceRef.current = parseFloat(data.bitcoin) * rate; | ||
| } | ||
| }; | ||
| const interval = setInterval(() => { | ||
| setPrevPrice((p) => price); | ||
| setPrice(priceRef.current); | ||
| }, 1000); | ||
| return () => { | ||
| ws.close(); | ||
| clearInterval(interval); | ||
| }; | ||
| }, [rate, price]); | ||
|
|
||
| useEffect(() => { | ||
| if (prevPrice === null || price === null) return; | ||
| if (price === prevPrice) return; | ||
| setTrend(price > prevPrice ? "up" : "down"); | ||
| const timeout = setTimeout(() => setTrend(null), 500); | ||
| return () => clearTimeout(timeout); | ||
| }, [price, prevPrice]); | ||
|
|
||
| if (price === null) { | ||
| return <div className="text-sm text-gray-400">Loading BTC price...</div>; | ||
| } | ||
|
|
||
| const trendClass = | ||
| trend === "up" ? "text-green-400" : trend === "down" ? "text-red-400" : "text-white"; | ||
|
|
||
| return ( | ||
| <motion.div | ||
| key={price} | ||
| initial={{ scale: 1 }} | ||
| animate={{ scale: [1, 1.05, 1] }} | ||
| transition={{ duration: 0.5 }} | ||
| className={`text-sm font-medium ${trendClass}`} | ||
| > | ||
| BTC Price: රු {price.toLocaleString("en-LK", { maximumFractionDigits: 0 })} | ||
| </motion.div> | ||
| ); | ||
| } | ||
|
|
||
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🛠️ Refactor suggestion
Fix WebSocket re-creation loop and incorrect prevPrice update
Including price in the effect’s dependency array recreates the WebSocket and timer on every update (roughly every second), causing churn and potential rate limits. Also, setPrevPrice((p) => price) ignores the functional param and does not reliably capture the previously displayed price.
Add a ref for the displayed price somewhere near existing refs:
Then replace the effect as below:
Also applies to: 45-51
🤖 Prompt for AI Agents