refactor(dashboard-v2): make CurrentPlan component use PlansProvider

This commit is contained in:
Michał Leszczyk 2022-03-04 12:03:52 +01:00
parent 8eacf13806
commit f1262fb8f7
No known key found for this signature in database
GPG Key ID: FA123CA8BAA2FBF4
4 changed files with 27 additions and 32 deletions

View File

@ -2,7 +2,7 @@ import dayjs from "dayjs";
import relativeTime from "dayjs/plugin/relativeTime";
import { useUser } from "../../contexts/user";
import useSubscriptionPlans from "../../hooks/useSubscriptionPlans";
import useActivePlan from "../../hooks/useActivePlan";
import LatestPayment from "./LatestPayment";
import SuggestedPlan from "./SuggestedPlan";
@ -11,7 +11,7 @@ dayjs.extend(relativeTime);
const CurrentPlan = () => {
const { user, error: userError } = useUser();
const { activePlan, plans, error: plansError } = useSubscriptionPlans(user);
const { plans, activePlan, error: plansError } = useActivePlan(user);
if (!user || !activePlan) {
return (

View File

@ -0,0 +1,22 @@
import { useEffect, useState } from "react";
import freeTier from "../lib/tiers";
import { usePlans } from "../contexts/plans";
export default function useActivePlan(user) {
const { plans, error } = usePlans();
const [activePlan, setActivePlan] = useState(freeTier);
useEffect(() => {
if (user) {
setActivePlan(plans.find((plan) => plan.tier === user.tier));
}
}, [plans, user]);
return {
error,
plans,
activePlan,
};
}

View File

@ -1,28 +0,0 @@
import { useEffect, useState } from "react";
import useSWR from "swr";
import freeTier from "../lib/tiers";
export default function useSubscriptionPlans(user) {
const { data: paidPlans, error, mutate } = useSWR("stripe/prices");
const [plans, setPlans] = useState([freeTier]);
const [activePlan, setActivePlan] = useState(freeTier);
useEffect(() => {
if (paidPlans) {
setPlans((plans) => [...plans, ...paidPlans].sort((planA, planB) => planA.tier - planB.tier));
}
}, [paidPlans]);
useEffect(() => {
if (user) {
setActivePlan(plans.find((plan) => plan.tier === user.tier));
}
}, [plans, user]);
return {
error,
mutate,
plans,
activePlan,
};
}

View File

@ -2,6 +2,7 @@ import * as React from "react";
import { useMedia } from "react-use";
import theme from "../lib/theme";
import { PlansProvider } from "../contexts/plans/PlansProvider";
import { ArrowRightIcon } from "../components/Icons";
import { Panel } from "../components/Panel";
import { Tab, TabPanel, Tabs } from "../components/Tabs";
@ -16,7 +17,7 @@ const IndexPage = () => {
const showRecentActivity = useMedia(`(min-width: ${theme.screens.md})`);
return (
<>
<PlansProvider>
<div className="w-full">
<Slider
slides={[
@ -60,7 +61,7 @@ const IndexPage = () => {
<LatestActivity />
</div>
)}
</>
</PlansProvider>
);
};