Skip to content
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 4 commits into from Mar 8, 2024
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
297 changes: 292 additions & 5 deletions package-lock.json

Large diffs are not rendered by default.

1 change: 1 addition & 0 deletions package.json
Expand Up @@ -25,6 +25,7 @@
"react-dom": "^18",
"react-icons": "^5.0.1",
"react-redux": "^9.1.0",
"recharts": "^2.12.1",
"tailwind-merge": "^2.2.1",
"tailwindcss-animate": "^1.0.7"
},
Expand Down
9 changes: 8 additions & 1 deletion src/app/components/CarouselCoins.tsx
Expand Up @@ -7,6 +7,7 @@ import { AppDispatch, useAppSelector } from "../../redux/store";
import { getCoinData } from "../../redux/features/coinInfoSlice";
import { ChevronUpIcon } from "../icons/ChevronUpIcon";
import { ChevronDownIcon } from "../icons/ChevronDownIcon";

import {
Carousel,
CarouselContent,
Expand All @@ -31,6 +32,9 @@ export default function CarouselCoins() {
if (isLoading) return <div>Loading...</div>;
if (hasError) return <div>Error loading the data.</div>;

const handleCarousel = (coin: string) => {
//implement in next PR
};
return (
<Carousel
opts={{
Expand All @@ -44,7 +48,10 @@ export default function CarouselCoins() {
key={coin.id}
className="sm:basis-1/2 md:basis-1/3 lg:basis-1/4 xl:basis-1/5"
>
<div className="h-[88px] dark:bg-[#191925] bg-[#FFFFFF] flex items-center rounded-lg cursor-pointer">
<div
onClick={() => handleCarousel(coin.id)}
Copy link
Collaborator

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.

className="h-[88px] dark:bg-[#191925] bg-[#FFFFFF] flex items-center rounded-lg cursor-pointer"
>
<div className="px-4">
<Image
src={coin.image}
Expand Down
11 changes: 11 additions & 0 deletions src/app/components/GraphCoins.tsx
@@ -0,0 +1,11 @@
import PriceChart from "./PriceChart";
import VolumeChart from "./VolumeChart";

export default function GraphCoins() {
return (
<div className="w-full flex gap-8">
<PriceChart />
<VolumeChart />
</div>
);
}
110 changes: 110 additions & 0 deletions src/app/components/PriceChart.tsx
@@ -0,0 +1,110 @@
"use client";
import { useDispatch } from "react-redux";
import { useEffect, useState } from "react";
import { XAxis, Tooltip, ResponsiveContainer, AreaChart, Area } from "recharts";
import { AppDispatch, useAppSelector } from "../../redux/store";
import { getCoinDataGraph } from "../../redux/features/selectedCoinSlice";

export default function PriceChart() {
const dispatch: AppDispatch = useDispatch();
const { selectedCoins, loading, hasError } = useAppSelector(
(state) => state.selectedCoin
);

const currencyCode = useAppSelector(
(state) => state.currency.currentCurrency.code
);
const currencySimbol = useAppSelector(
(state) => state.currency.currentCurrency.symbol
);

const [currentPriceCoin, setCurrentPriceCoin] = useState("");
const [currentDate, setCurrentDate] = useState("");

useEffect(() => {
dispatch(
getCoinDataGraph({
currency: currencyCode,
days: "3",
coinId: "bitcoin",
})
);
}, [dispatch, currencyCode]);

useEffect(() => {
if (selectedCoins.length > 0) {
const lastDataPoint =
selectedCoins[0].prices[selectedCoins[0].prices.length - 1];
const lastPrice = lastDataPoint[1];
const lastDate = new Date(lastDataPoint[0]).toLocaleDateString();

setCurrentPriceCoin(`${lastPrice.toFixed(2)}`);
setCurrentDate(lastDate);
}
}, [selectedCoins, currencyCode]);

if (loading === "pending") {
return <div>Loading...</div>;
}

if (hasError) {
return <div>Error fetching data</div>;
}

const coin = selectedCoins.length > 0 ? selectedCoins[0] : null;
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You can take selectedCoins.length in a variable.


const formattedData = coin
? coin.prices.map(([time, price]) => ({
date: new Date(time).toLocaleDateString(),
price,
}))
: [];

const handleMouseMove = (e: any) => {
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why are we using any in typescript, it should have proper typing.

Copy link
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I've fixed it. I'll push the code soon.

if (e.activePayload && e.activePayload.length > 0) {
const { payload } = e.activePayload[0];
setCurrentPriceCoin(`${payload.price.toFixed(2)}`);
setCurrentDate(payload.date);
}
};

return (
<div className="w-1/2 h-[404px] flex flex-col dark:bg-[#191932] bg-white rounded-xl p-6">
<div className="flex flex-col">
<span className="text-xl font-normal dark:text-[#D1D1D1] text-[#191932] leading-6">
{coin
? coin.id.charAt(0).toUpperCase() + coin.id.slice(1)
: "Loading..."}
</span>
<span className="text-[28px] font-bold leading-7 mt-6">
{currentPriceCoin
? `${currencySimbol}${currentPriceCoin}`
: "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}>
<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="price"
stroke="#7878FA"
strokeWidth="3"
fill="url(#color)"
/>

<XAxis dataKey="date" axisLine={false} tickLine={false} />

<Tooltip content={<></>} />
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why does Tooltip don't have any content?

Copy link
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't want to display anything in Tooltip because I'm displaying updated price outside chart. When I'm hovering over chart it is updating price number outside chart. Tooltip is used to display information inside chart as a box which is displayed when you hover over chart. If I delete content={<></>} inside tooltip i will have the same information presented twice, price will be displayed as a box inside chart and outside chart because I specified to have a price outside chart with the name of coin and date.

</AreaChart>
</ResponsiveContainer>
</div>
);
}
106 changes: 106 additions & 0 deletions src/app/components/VolumeChart.tsx
@@ -0,0 +1,106 @@
"use client";
import { useDispatch } from "react-redux";
import { useEffect, useState } from "react";
import { BarChart, Bar, XAxis, Tooltip, ResponsiveContainer } from "recharts";
import { AppDispatch, useAppSelector } from "../../redux/store";
import { getCoinDataGraph } from "../../redux/features/selectedCoinSlice";
import formatNumber from "../utils/formatNumber";

export default function VolumeChart() {
const dispatch: AppDispatch = useDispatch();
const { selectedCoins, loading, hasError } = useAppSelector(
(state) => state.selectedCoin
);

const currencyCode = useAppSelector(
(state) => state.currency.currentCurrency.code
);
const currencySimbol = useAppSelector(
(state) => state.currency.currentCurrency.symbol
);
const [currentVolume, setCurrentVolume] = useState("");
const [currentDateVolume, setCurrentDateVolume] = useState("");

useEffect(() => {
dispatch(
getCoinDataGraph({
currency: currencyCode,
days: "3",
coinId: "bitcoin",
})
);
}, [dispatch, currencyCode]);

useEffect(() => {
if (selectedCoins.length > 0) {
const lastDataPoint =
selectedCoins[0].total_volumes[
selectedCoins[0].total_volumes.length - 1
];
const lastTotalVolume = lastDataPoint[1];
const lastDate = new Date(lastDataPoint[0]).toLocaleDateString();

setCurrentVolume(`${lastTotalVolume.toFixed(2)}`);
setCurrentDateVolume(lastDate);
}
}, [selectedCoins, 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 formattedDataVolume = coin
? coin.total_volumes.map(([time, volume]) => ({
date: new Date(time).toLocaleDateString(),
volume,
}))
: [];

const handleMouseMoveOnVolume = (e: any) => {
if (e.activePayload && e.activePayload.length > 0) {
const { payload } = e.activePayload[0];
setCurrentVolume(`${payload.volume.toFixed(2)}`);
setCurrentDateVolume(payload.date);
}
};

return (
<div className="w-1/2 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">
Volume 24h
</span>
<span className="text-[28px] font-bold leading-7 mt-6">
{currentVolume
? `${currencySimbol}${formatNumber(parseFloat(currentVolume))}`
: "Fetching..."}
</span>
<span className="text-base font-normal dark:text-[#B9B9BA] text-[#424286] leading-6 mt-4">
{currentDateVolume}
</span>
</div>
<ResponsiveContainer width="100%" height={266}>
<BarChart
data={formattedDataVolume}
onMouseMove={handleMouseMoveOnVolume}
>
<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>
</ResponsiveContainer>
</div>
);
}
4 changes: 4 additions & 0 deletions src/app/page.tsx
@@ -1,5 +1,6 @@
import NavHome from "./components/NavHome";
import CarouselCoins from "./components/CarouselCoins";
import GraphCoins from "./components/GraphCoins";

export default function Home() {
return (
Expand All @@ -8,6 +9,9 @@ export default function Home() {
<div className="mt-[70px] max-w-[1440px] mx-auto xl:px-[72px] lg:px-[36px] md:px-[24px]">
<CarouselCoins />
</div>
<div className="mt-10 max-w-[1440px] mx-auto xl:px-[72px] lg:px-[36px] md:px-[24px]">
<GraphCoins />
</div>
</main>
);
}
78 changes: 78 additions & 0 deletions src/redux/features/selectedCoinSlice.ts
@@ -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;
2 changes: 2 additions & 0 deletions src/redux/store.ts
Expand Up @@ -4,12 +4,14 @@ import { configureStore } from "@reduxjs/toolkit";
import globalReducer from "./features/globalSlice";
import currencyReducer from "./features/currencySlice";
import coinReducer from "./features/coinInfoSlice";
import selectedCoinReducer from "./features/selectedCoinSlice";

export const store = configureStore({
reducer: {
globalData: globalReducer,
currency: currencyReducer,
coinData: coinReducer,
selectedCoin: selectedCoinReducer,
},
});

Expand Down