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
feat/graph-coins #6
Merged
Merged
Changes from all commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
f1f2580
installed recharts js
bonz88 6cd3935
added handleCarousel, i will solve it in next PR
bonz88 86452b5
added area and bar graph for displaying bitcoin data
bonz88 9a093c1
refactored to use one component for Price and Volume chart, replaced …
bonz88 File filter
Filter by extension
Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
There are no files selected for viewing
Large diffs are not rendered by default.
Oops, something went wrong.
This file contains 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 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 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,148 @@ | ||
"use client"; | ||
import { useEffect, useState } from "react"; | ||
import { useDispatch } from "react-redux"; | ||
import { | ||
BarChart, | ||
Bar, | ||
XAxis, | ||
Tooltip, | ||
ResponsiveContainer, | ||
AreaChart, | ||
Area, | ||
} from "recharts"; | ||
import { AppDispatch, useAppSelector } from "../../redux/store"; | ||
import { getCoinDataGraph } from "../../redux/features/selectedCoinSlice"; | ||
import formatNumber from "../utils/formatNumber"; | ||
|
||
type Payload = { | ||
date: string; | ||
value?: number; | ||
volume?: number; | ||
}; | ||
|
||
type CoinChartProps = { | ||
chartType: "price" | "volume"; | ||
currencyCode: string; | ||
currencySymbol?: string; | ||
}; | ||
|
||
export default function CoinChart({ | ||
chartType, | ||
currencyCode, | ||
currencySymbol, | ||
}: CoinChartProps) { | ||
const dispatch: AppDispatch = useDispatch(); | ||
const { selectedCoins, loading, hasError } = useAppSelector( | ||
(state) => state.selectedCoin | ||
); | ||
const [currentValue, setCurrentValue] = useState(""); | ||
const [currentDate, setCurrentDate] = useState(""); | ||
|
||
useEffect(() => { | ||
dispatch( | ||
getCoinDataGraph({ currency: currencyCode, days: "3", coinId: "bitcoin" }) | ||
); | ||
}, [dispatch, currencyCode]); | ||
|
||
useEffect(() => { | ||
if (selectedCoins.length > 0) { | ||
const lastDataPoint = | ||
chartType === "price" | ||
? selectedCoins[0].prices[selectedCoins[0].prices.length - 1] | ||
: selectedCoins[0].total_volumes[ | ||
selectedCoins[0].total_volumes.length - 1 | ||
]; | ||
const lastValue = lastDataPoint[1]; | ||
const lastDate = new Date(lastDataPoint[0]).toLocaleDateString(); | ||
|
||
setCurrentValue(`${lastValue.toFixed(2)}`); | ||
setCurrentDate(lastDate); | ||
} | ||
}, [selectedCoins, chartType, currencyCode]); | ||
|
||
if (loading === "pending") { | ||
return <div>Loading...</div>; | ||
} | ||
|
||
if (hasError) { | ||
return <div>Error fetching data</div>; | ||
} | ||
|
||
const coin = selectedCoins.length > 0 ? selectedCoins[0] : null; | ||
|
||
const formattedData = coin | ||
? chartType === "price" | ||
? coin.prices.map(([time, value]) => ({ | ||
date: new Date(time).toLocaleDateString(), | ||
value, | ||
})) | ||
: coin.total_volumes.map(([time, volume]) => ({ | ||
date: new Date(time).toLocaleDateString(), | ||
volume, | ||
})) | ||
: []; | ||
|
||
const handleMouseMove = (e: { activePayload?: { payload: Payload }[] }) => { | ||
if (e.activePayload && e.activePayload.length > 0) { | ||
const { payload } = e.activePayload[0]; | ||
const dataKey = chartType === "price" ? "value" : "volume"; | ||
const value = payload[dataKey]?.toFixed(2) ?? "0"; | ||
setCurrentValue(value); | ||
setCurrentDate(payload.date); | ||
} | ||
}; | ||
|
||
return ( | ||
<div className="w-full h-[404px] flex flex-col dark:bg-[#1E1932] bg-white rounded-xl p-6"> | ||
<div className="flex flex-col"> | ||
<span className="text-xl font-normal dark:text-[#D1D1D1] text-[#191932] leading-6"> | ||
{chartType === "volume" | ||
? "Volume 24h" | ||
: `${coin?.id.charAt(0).toUpperCase()}${coin?.id.slice(1)}`} | ||
</span> | ||
<span className="text-[28px] font-bold leading-7 mt-6"> | ||
{currentValue | ||
? `${currencySymbol}${formatNumber(parseFloat(currentValue))}` | ||
: "Fetching..."} | ||
</span> | ||
<span className="text-base font-normal dark:text-[#B9B9BA] text-[#424286] leading-6 mt-4"> | ||
{currentDate} | ||
</span> | ||
</div> | ||
<ResponsiveContainer width="100%" height={266}> | ||
{chartType === "volume" ? ( | ||
<BarChart data={formattedData} onMouseMove={handleMouseMove}> | ||
<defs> | ||
<linearGradient id="color" x1="0" y1="0" x2="0" y2="1"> | ||
<stop offset="1%" stopColor="#B374F2" /> | ||
<stop offset="100%" stopColor="#9D62D9" /> | ||
</linearGradient> | ||
</defs> | ||
<XAxis dataKey="date" /> | ||
<Tooltip content={<></>} /> | ||
<Bar dataKey="volume" stroke="" fill="url(#color)" /> | ||
</BarChart> | ||
) : ( | ||
<AreaChart data={formattedData} onMouseMove={handleMouseMove}> | ||
<defs> | ||
<linearGradient id="color" x1="0" y1="0" x2="0" y2="1"> | ||
<stop offset="1%" stopColor="#7474F2" stopOpacity={0.6} /> | ||
<stop offset="60%" stopColor="#7474F2" stopOpacity={0.1} /> | ||
</linearGradient> | ||
</defs> | ||
<Area | ||
dataKey="value" | ||
stroke="#7878FA" | ||
strokeWidth="3" | ||
fill="url(#color)" | ||
/> | ||
|
||
<XAxis dataKey="date" axisLine={false} tickLine={false} /> | ||
|
||
<Tooltip content={<></>} /> | ||
</AreaChart> | ||
)} | ||
</ResponsiveContainer> | ||
</div> | ||
); | ||
} |
This file contains 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,26 @@ | ||
"use client"; | ||
import CoinChart from "./CoinChart"; | ||
import { useAppSelector } from "../../redux/store"; | ||
|
||
export default function GraphCoins() { | ||
const currencyCode = useAppSelector( | ||
(state) => state.currency.currentCurrency.code | ||
); | ||
const currencySimbol = useAppSelector( | ||
(state) => state.currency.currentCurrency.symbol | ||
); | ||
return ( | ||
<div className="w-full flex gap-8"> | ||
<CoinChart | ||
chartType="price" | ||
currencyCode={currencyCode} | ||
currencySymbol={currencySimbol} | ||
/> | ||
<CoinChart | ||
chartType="volume" | ||
currencyCode={currencyCode} | ||
currencySymbol={currencySimbol} | ||
/> | ||
</div> | ||
); | ||
} |
This file contains 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 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,78 @@ | ||
"use client"; | ||
|
||
import { createSlice, createAsyncThunk } from "@reduxjs/toolkit"; | ||
|
||
type GetCoinDataArgs = { | ||
currency: string; | ||
days: string; | ||
coinId: string; | ||
}; | ||
|
||
type CoinData = { | ||
id: string; | ||
prices: [number, number][]; | ||
total_volumes: [number, number][]; | ||
}; | ||
|
||
type selectedCoinState = { | ||
selectedCoins: CoinData[]; | ||
loading: string; | ||
hasError: boolean; | ||
}; | ||
|
||
const initialState: selectedCoinState = { | ||
selectedCoins: [], | ||
loading: "idle", | ||
hasError: false, | ||
}; | ||
|
||
export const getCoinDataGraph = createAsyncThunk( | ||
"coinData/getCoinData", | ||
async ({ currency, days, coinId }: GetCoinDataArgs, { rejectWithValue }) => { | ||
try { | ||
const response = await fetch( | ||
`https://api.coingecko.com/api/v3/coins/${coinId}/market_chart?vs_currency=${currency}&days=${days}?x_cg_demo_api_key=${process.env.NEXT_PUBLIC_API_KEY}` | ||
); | ||
|
||
if (!response.ok) { | ||
throw new Error("Network response was not ok"); | ||
} | ||
|
||
const data = await response.json(); | ||
const { prices, total_volumes } = data; | ||
const item: CoinData = { | ||
id: coinId, | ||
prices, | ||
total_volumes, | ||
}; | ||
return item; | ||
} catch (error: any) { | ||
return rejectWithValue(error.message); | ||
} | ||
} | ||
); | ||
|
||
const selectedCoinsSlice = createSlice({ | ||
name: "selectedCoin", | ||
initialState, | ||
reducers: {}, | ||
|
||
extraReducers: (builder) => { | ||
builder | ||
.addCase(getCoinDataGraph.pending, (state) => { | ||
state.loading = "pending"; | ||
state.hasError = false; | ||
}) | ||
.addCase(getCoinDataGraph.fulfilled, (state, action) => { | ||
state.selectedCoins = [action.payload]; | ||
state.loading = "fulfilled"; | ||
}) | ||
.addCase(getCoinDataGraph.rejected, (state, action) => { | ||
state.loading = "rejected"; | ||
state.hasError = true; | ||
console.error("API call failed with error:", action.payload); | ||
}); | ||
}, | ||
}); | ||
|
||
export default selectedCoinsSlice.reducer; |
This file contains 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
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.
We should not add onClick on a div, it is semantically not correct. You should replace this div with a button and remove the styling if you don't want styling.