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

122 migrate from jotai to zustand #123

Merged
merged 3 commits into from
Sep 7, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 0 additions & 6 deletions app/Providers.tsx

This file was deleted.

9 changes: 4 additions & 5 deletions app/components/HistoricalResult.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,20 +2,19 @@

import { ResponsiveLine } from "@nivo/line";
import { parse, subMonths } from "date-fns";
import { useAtomValue } from "jotai";
import { showCategoriesAtom } from "@/atoms/coeAtom";
import useStore from "@/app/store";
import type { COEResult } from "@/types";

interface QuotaPremium {
[key: string]: { [key: string]: number };
}

interface HistoricalResultProps {
interface Props {
data: COEResult[];
}

export const HistoricalResult = ({ data }: HistoricalResultProps) => {
const categories = useAtomValue(showCategoriesAtom);
export const HistoricalResult = ({ data }: Props) => {
const categories = useStore(({ categories }) => categories);
const filteredData = data.filter((item) => categories[item.vehicle_class]);

const processCOEData = (data: COEResult[]) => {
Expand Down
22 changes: 9 additions & 13 deletions app/components/KeyStatistics.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
"use client";

import useStore from "@/app/store";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import {
Select,
Expand All @@ -8,14 +9,14 @@ import {
SelectTrigger,
SelectValue,
} from "@/components/ui/select";
import { useGlobalState } from "@/context/GlobalStateContext";

interface KeyStatisticsProps {
interface Props {
data: { year: number; total: number }[];
}

export const KeyStatistics = ({ data }: KeyStatisticsProps) => {
const { state, dispatch } = useGlobalState();
export const KeyStatistics = ({ data }: Props) => {
const selectedYear = useStore(({ selectedYear }) => selectedYear);
const setSelectedYear = useStore(({ setSelectedYear }) => setSelectedYear);

return (
<Card>
Expand All @@ -26,10 +27,8 @@ export const KeyStatistics = ({ data }: KeyStatisticsProps) => {
<div className="space-y-2">
<div>
<Select
onValueChange={(year) =>
dispatch({ type: "SET_SELECTED_YEAR", payload: year })
}
defaultValue={state.selectedYear}
onValueChange={(year) => setSelectedYear(year)}
defaultValue={selectedYear}
>
<SelectTrigger className="w-[180px]">
<SelectValue placeholder="Select year" />
Expand All @@ -46,11 +45,8 @@ export const KeyStatistics = ({ data }: KeyStatisticsProps) => {
</Select>
</div>
<p>
Total Registrations in {state.selectedYear}:{" "}
{
data.find((item) => item.year.toString() === state.selectedYear)
?.total
}
Total Registrations in {selectedYear}:{" "}
{data.find((item) => item.year.toString() === selectedYear)?.total}
</p>
<p>
Highest Year:{" "}
Expand Down
9 changes: 4 additions & 5 deletions app/components/MonthlyResult.tsx
Original file line number Diff line number Diff line change
@@ -1,16 +1,15 @@
"use client";

import { ResponsiveBar } from "@nivo/bar";
import { useAtomValue } from "jotai";
import { showCategoriesAtom } from "@/atoms/coeAtom";
import useStore from "@/app/store";
import type { COEResult } from "@/types";

interface MonthlyResultProps {
interface Props {
data: COEResult[];
}

export const MonthlyResult = ({ data }: MonthlyResultProps) => {
const categories = useAtomValue(showCategoriesAtom);
export const MonthlyResult = ({ data }: Props) => {
const categories = useStore(({ categories }) => categories);
const filteredData = data.filter(
(item: COEResult) => categories[item.vehicle_class],
);
Expand Down
18 changes: 6 additions & 12 deletions app/layout.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,11 @@ import React from "react";
import { Inter } from "next/font/google";
import { GoogleAnalytics } from "@next/third-parties/google";
import classNames from "classnames";
import { Providers } from "@/app/Providers";
import { Announcement } from "@/app/components/Announcement";
import { Footer } from "@/app/components/Footer";
import { Header } from "@/app/components/Header";
import { ANNOUNCEMENT, SITE_TITLE, SITE_URL } from "@/config";
import "./globals.css";
import { GlobalStateProvider } from "@/context/GlobalStateContext";
import { Analytics } from "./components/Analytics";
import type { Metadata } from "next";

Expand Down Expand Up @@ -50,16 +48,12 @@ const RootLayout = async ({ children }: { children: React.ReactNode }) => {
return (
<html lang="en">
<body className={classNames(inter.className, "bg-gray-50 text-gray-900")}>
<GlobalStateProvider>
{ANNOUNCEMENT && <Announcement>{ANNOUNCEMENT}</Announcement>}
<Header />
<Providers>
<main className="container mx-auto min-h-screen px-4 py-16">
{children}
</main>
</Providers>
<Footer />
</GlobalStateProvider>
{ANNOUNCEMENT && <Announcement>{ANNOUNCEMENT}</Announcement>}
<Header />
<main className="container mx-auto min-h-screen px-4 py-16">
{children}
</main>
<Footer />
<Analytics />
</body>
<GoogleAnalytics gaId={gaMeasurementId} />
Expand Down
30 changes: 30 additions & 0 deletions app/store.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
import { create } from "zustand";
import { persist } from "zustand/middleware";
import {
type COEAction,
type CoeSlice,
createCoeSlice,
} from "@/app/store/coeSlice";
import {
createDateSlice,
type DateAction,
type DateState,
} from "@/app/store/dateSlice";

type State = DateState & CoeSlice;
type Action = DateAction & COEAction;

const useStore = create<State & Action, [["zustand/persist", unknown]]>(
persist(
(...a) => ({
...createDateSlice(...a),
...createCoeSlice(...a),
}),
{
name: "config",
partialize: ({ categories }) => ({ categories }),
},
),
);

export default useStore;
29 changes: 29 additions & 0 deletions app/store/coeSlice.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
import type { COECategoryFilter, COECategory } from "@/types";
import type { StateCreator } from "zustand";

export type CoeSlice = {
categories: COECategoryFilter;
};

export type COEAction = {
updateCategories: (category: COECategory) => void;
};

const defaultCategories: COECategoryFilter = {
"Category A": true,
"Category B": true,
"Category C": false,
"Category D": false,
"Category E": true,
};

export const createCoeSlice: StateCreator<CoeSlice & COEAction> = (set) => ({
categories: defaultCategories,
updateCategories: (category) =>
set(({ categories }) => ({
categories: {
...categories,
[category]: !categories[category],
},
})),
});
18 changes: 18 additions & 0 deletions app/store/dateSlice.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import type { StateCreator } from "zustand";

export type DateState = {
selectedMonth: string;
selectedYear: string;
};

export type DateAction = {
setSelectedMonth: (month: string) => void;
setSelectedYear: (year: string) => void;
};

export const createDateSlice: StateCreator<DateState & DateAction> = (set) => ({
selectedMonth: "",
selectedYear: (new Date().getFullYear() - 1).toString(),
setSelectedMonth: (selectedMonth) => set(() => ({ selectedMonth })),
setSelectedYear: (selectedYear) => set(() => ({ selectedYear })),
});
12 changes: 0 additions & 12 deletions atoms/coeAtom.ts

This file was deleted.

16 changes: 8 additions & 8 deletions components/COEPremiumChart.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
"use client";

import { useAtomValue } from "jotai";
import {
CartesianGrid,
Legend,
Expand All @@ -11,25 +10,26 @@ import {
XAxis,
YAxis,
} from "recharts";
import { showCategoriesAtom } from "@/atoms/coeAtom";
import useStore from "@/app/store";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { formatDateToMonthYear } from "@/utils/formatDateToMonthYear";
import type { COEBiddingResult } from "@/types";
import type { COEBiddingResult, COECategory } from "@/types";

interface COEPremiumChartProps {
interface Props {
data: COEBiddingResult[];
}

export const COEPremiumChart = ({ data }: COEPremiumChartProps) => {
const filterCategories = useAtomValue(showCategoriesAtom);
export const COEPremiumChart = ({ data }: Props) => {
const categories = useStore(({ categories }) => categories);
const filteredData: COEBiddingResult[] = data.map((item) =>
Object.entries(item).reduce((acc: any, [key, value]) => {
if (
key === "month" ||
(key.startsWith("Category") && filterCategories[key])
(key.startsWith("Category") && categories[key as COECategory])
) {
acc[key] = value;
}

return acc;
}, {}),
);
Expand Down Expand Up @@ -58,7 +58,7 @@ export const COEPremiumChart = ({ data }: COEPremiumChartProps) => {
<YAxis />
<Tooltip />
<Legend />
{Object.entries(filterCategories)
{Object.entries(categories)
.sort(([a], [b]) => a.localeCompare(b))
.map(
([category, value], index) =>
Expand Down
18 changes: 8 additions & 10 deletions components/CategoryInfo.tsx
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
"use client";

import { useAtom } from "jotai";
import { showCategoriesAtom } from "@/atoms/coeAtom";
import useStore from "@/app/store";
import { cn } from "@/lib/utils";
import type { COECategory } from "@/types";
import type { LucideIcon } from "lucide-react";

interface CategoryInfoProps {
interface Props {
icon: LucideIcon;
category: string;
category: COECategory;
description: string;
canFilter?: boolean;
}
Expand All @@ -17,15 +17,13 @@ export const CategoryInfo = ({
category,
description,
canFilter = true,
}: CategoryInfoProps) => {
const [categories, setCategories] = useAtom(showCategoriesAtom);
}: Props) => {
const categories = useStore((state) => state.categories);
const updateCategories = useStore((state) => state.updateCategories);

const handleFilterCategories = () => {
if (canFilter) {
setCategories((categories) => ({
...categories,
[category]: !categories[category],
}));
updateCategories(category);
}
};

Expand Down
13 changes: 7 additions & 6 deletions components/MonthSelector.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

import { useCallback, useEffect, useMemo } from "react";
import { usePathname, useRouter, useSearchParams } from "next/navigation";
import useStore from "@/app/store";
import {
Select,
SelectContent,
Expand All @@ -11,7 +12,6 @@ import {
SelectTrigger,
SelectValue,
} from "@/components/ui/select";
import { useGlobalState } from "@/context/GlobalStateContext";
import { formatDateToMonthYear } from "@/utils/formatDateToMonthYear";
import { groupByYear } from "@/utils/groupByYear";

Expand All @@ -20,16 +20,17 @@ interface Props {
}

export const MonthSelector = ({ months }: Props) => {
const { dispatch, state } = useGlobalState();
const router = useRouter();
const pathname = usePathname();
const searchParams = useSearchParams();

const month = searchParams.get("month");

const selectedMonth = useStore((state) => state.selectedMonth);
const setSelectedMonth = useStore((state) => state.setSelectedMonth);

useEffect(() => {
dispatch({ type: "SET_SELECTED_MONTH", payload: month ?? months[0] });
}, [dispatch, month, months]);
setSelectedMonth(month ?? months[0]);
}, [month, months, setSelectedMonth]);

const memoisedGroupByYear = useMemo(() => groupByYear, []);
const sortedMonths = useMemo(
Expand All @@ -47,7 +48,7 @@ export const MonthSelector = ({ months }: Props) => {

return (
<div>
<Select value={state.selectedMonth} onValueChange={handleValueChange}>
<Select value={selectedMonth} onValueChange={handleValueChange}>
<SelectTrigger>
<SelectValue placeholder="Select Month" />
</SelectTrigger>
Expand Down
Loading