Skip to content

Commit

Permalink
Merge pull request #295 from The-Creative-Programming-Group/url-searc…
Browse files Browse the repository at this point in the history
…h-params

feat: Added URL Search Params and updated tRPC
  • Loading branch information
FleetAdmiralJakob authored Mar 23, 2024
2 parents d90c2c5 + a0e1188 commit b64e644
Show file tree
Hide file tree
Showing 14 changed files with 240 additions and 280 deletions.
12 changes: 6 additions & 6 deletions apps/web/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -18,12 +18,12 @@
"@legendapp/state": "^2.1.8",
"@next/bundle-analyzer": "^14.1.3",
"@t3-oss/env-nextjs": "^0.9.2",
"@tanstack/react-query": "^4.36.1",
"@tanstack/react-query-devtools": "^4.36.1",
"@trpc/client": "^10.45.2",
"@trpc/next": "^10.45.2",
"@trpc/react-query": "^10.45.2",
"@trpc/server": "^10.45.2",
"@tanstack/react-query": "^5.28.6",
"@tanstack/react-query-devtools": "^5.28.6",
"@trpc/client": "^11.0.0-next-beta.318",
"@trpc/next": "^11.0.0-next-beta.318",
"@trpc/react-query": "^11.0.0-next-beta.318",
"@trpc/server": "^11.0.0-next-beta.318",
"@vercel/analytics": "^1.2.2",
"@vercel/speed-insights": "^1.0.10",
"@weatherio/api": "workspace:^0.1.0",
Expand Down
6 changes: 5 additions & 1 deletion apps/web/src/components/Layout.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import { PiScrollFill } from "react-icons/pi";
import { cn } from "@weatherio/ui";

import { useScopedI18n } from "~/locales";
import { activeCity$ } from "~/states";

interface LayoutProps {
title?: string;
Expand Down Expand Up @@ -121,7 +122,10 @@ const Layout: React.FC<LayoutProps> = ({
/>
)}
<Link
href="/home"
href={{
pathname: "/home",
query: { cityId: activeCity$.id.get() },
}}
className="ml-2.5 flex flex-col items-center text-xl font-semibold"
>
<h1>{translation("title")}</h1>
Expand Down
14 changes: 7 additions & 7 deletions apps/web/src/lib/utils/api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,13 +20,6 @@ const getBaseUrl = () => {
export const api = createTRPCNext<AppRouter>({
config() {
return {
/**
* Transformer used for data deserialization from the server.
*
* @see https://trpc.io/docs/data-transformers
*/
transformer: superjson,

/**
* Links used to determine request flow from client to server.
*
Expand All @@ -40,6 +33,12 @@ export const api = createTRPCNext<AppRouter>({
}),
httpBatchLink({
url: `${getBaseUrl()}/api/trpc`,
/**
* Transformer used for data deserialization from the server.
*
* @see https://trpc.io/docs/data-transformers
*/
transformer: superjson,
}),
],
};
Expand All @@ -50,4 +49,5 @@ export const api = createTRPCNext<AppRouter>({
* @see https://trpc.io/docs/nextjs#ssr-boolean-default-false
*/
ssr: false,
transformer: superjson,
});
90 changes: 60 additions & 30 deletions apps/web/src/pages/home/index.tsx
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
import React, { useEffect, useLayoutEffect, useState } from "react";
import React, { useEffect, useState } from "react";
import dynamic from "next/dynamic";
import Link from "next/link";
import { useRouter } from "next/router";
import { observer } from "@legendapp/state/react";
import { skipToken } from "@tanstack/react-query";
import clsx from "clsx";
import { useQuery } from "convex/react";
import dayjs from "dayjs";
import timezone from "dayjs/plugin/timezone";
import utc from "dayjs/plugin/utc";
Expand All @@ -25,6 +27,7 @@ import { PiSunglasses } from "react-icons/pi";
import { WiRaindrop } from "react-icons/wi";

import type { IDailyForecast, IHourlyForecast } from "@weatherio/types";
import { api as convexApi } from "@weatherio/city-data";
import { Button } from "@weatherio/ui/button";
import {
Collapsible,
Expand Down Expand Up @@ -125,23 +128,48 @@ const InternalHome = observer(() => {
useState(false);
const [isMoreWarningsCollapsibleOpen, setIsMoreWarningsCollapsibleOpen] =
useState(false);
const { locale, query, replace, isReady } = useRouter();

const cityById = useQuery(
convexApi.getCity.findCityById,
typeof query.cityId === "string" ? { id: parseInt(query.cityId) } : "skip",
);

useEffect(() => {
const cityByIdIsLoading =
cityById === undefined && typeof query.cityId === "string";
if (!cityByIdIsLoading && !cityById && isReady) {
if (activeCity$.id.get() !== 0 && activeCity$.name.get() !== "") {
void replace("/home?cityId=" + activeCity$.id.get());
return;
} else {
void replace("/search");
return;
}
}
});

const { locale } = useRouter();
const weatherData = api.weather.getWeather.useQuery(
cityById
? {
coordinates: cityById.coord,
timezone: dayjs.tz.guess(),
lang: locale,
}
: skipToken,
// TODO: The cache (stale time) is not yet working if you refresh the page
{
coordinates: activeCity$.coord.get(),
timezone: dayjs.tz.guess(),
lang: locale,
refetchOnWindowFocus: false,
staleTime: 1000 * 60 * 60 /* 1 hour */,
},
// TODO: The cache (stale time) is not yet working if you refresh the page
{ refetchOnWindowFocus: false, staleTime: 1000 * 60 * 60 /* 1 hour */ },
);

let temperature = undefined;
if (weatherData.data?.temperature) {
temperature =
temperatureUnit$.get() === "Celsius"
? `${Math.round(weatherData.data?.temperature - 273.15)}°C`
: `${Math.round((weatherData.data?.temperature * 9) / 5 - 459.67)}°F`;
? `${Math.round(weatherData.data.temperature - 273.15)}°C`
: `${Math.round((weatherData.data.temperature * 9) / 5 - 459.67)}°F`;
}

const translationHome = useScopedI18n("home");
Expand Down Expand Up @@ -290,19 +318,9 @@ const InternalHome = observer(() => {
return translationHome("weather state sunny");
};

const mapPosition: [number, number] = [
activeCity$.coord.lat.get(),
activeCity$.coord.lon.get(),
];

const router = useRouter();

// Prevent a weather forecast for the preset active city from being displayed
useLayoutEffect(() => {
if (activeCity$.id.get() === 0 && activeCity$.name.get() === "") {
void router.push("/search");
}
});
const mapPosition: [number, number] | undefined = cityById
? [cityById.coord.lat, cityById.coord.lon]
: undefined;

const [isSafari, setIsSafari] = useState<boolean>(false);

Expand All @@ -325,10 +343,14 @@ const InternalHome = observer(() => {
}, []);

return (
<Layout classNameShareButton="mt-44" page="home">
<Layout
classNameShareButton="mt-44"
page="home"
title={cityById ? cityById.name : undefined}
>
<div className="mt-24 flex flex-col items-center">
<h1 className="text-center text-4xl sm:text-5xl md:text-7xl">
{activeCity$.name.get()}
{cityById ? cityById.name : <Skeleton className="h-20 w-80" />}
</h1>
<h1 className="mt-3 text-6xl text-gray-500 md:text-7xl">
{temperature ? temperature : <Skeleton className="h-20 w-36" />}
Expand Down Expand Up @@ -373,7 +395,7 @@ const InternalHome = observer(() => {
</p>
</div>
</div>
{weatherData?.data?.maxUVIndex && weatherData.data.sunHours ? (
{weatherData.data?.maxUVIndex && weatherData.data.sunHours ? (
<Collapsible
className="mt-2 flex w-full flex-col items-center"
open={isMoreInfoCollapsibleOpen}
Expand Down Expand Up @@ -1096,15 +1118,23 @@ const InternalHome = observer(() => {

<div className="z-0 col-span-2 col-start-8 row-span-4 row-start-1 hidden rounded-md bg-gray-400 md:block">
<div className="h-full w-full">
<Map
position={mapPosition}
className="h-full w-full rounded-md"
/>
{mapPosition ? (
<Map
position={mapPosition}
className="h-full w-full rounded-md"
/>
) : (
<Skeleton className="h-full w-full" />
)}
</div>
</div>
</div>
<div className="z-0 mb-6 block h-96 w-11/12 rounded-md md:hidden">
<Map position={mapPosition} className="h-full w-full rounded-md" />
{mapPosition ? (
<Map position={mapPosition} className="h-full w-full rounded-md" />
) : (
<Skeleton className="h-full w-full" />
)}
</div>
</div>
</Layout>
Expand Down
2 changes: 1 addition & 1 deletion apps/web/src/pages/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ const PublicHome: NextPage = () => {

useLayoutEffect(() => {
if (activeCity$.id.get() !== 0 && activeCity$.name.get() !== "") {
void router.push("/home");
void router.push("/home?cityId=" + activeCity$.id.get());
}
});

Expand Down
41 changes: 14 additions & 27 deletions apps/web/src/pages/locationsettings/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import React, { useEffect, useRef, useState } from "react";
import Image from "next/image";
import { observer } from "@legendapp/state/react";
import clsx from "clsx";
import { useQuery } from "convex/react";
import { useMutation, useQuery } from "convex/react";
import { RxCross2 } from "react-icons/rx";
import { ClipLoader } from "react-spinners";
import { toast } from "sonner";
Expand All @@ -13,7 +13,6 @@ import { api as convexApi } from "@weatherio/city-data";

import search2Image from "~/assets/search2.png";
import Layout from "~/components/Layout";
import { api as tRPCApi } from "~/lib/utils/api";
import { getLocaleProps, useScopedI18n } from "~/locales";
import { activeCity$, addedCities$ } from "~/states";

Expand Down Expand Up @@ -47,16 +46,9 @@ const LocationSettings = observer(() => {
id: searchValue.id,
});

const findCityByCoordinatesMutation =
tRPCApi.reverseGeoRouter.getCity.useMutation({
onSuccess: (data) => {
if (data) {
setSearchValue(data);
} else {
toast.error(translationLocationSettings("city not found toast"));
}
},
});
const findCityByCoordinatesMutation = useMutation(
convexApi.getCity.findNearestCityByCoord,
);

useEffect(() => {
if (searchValue.name === "") {
Expand Down Expand Up @@ -159,22 +151,9 @@ const LocationSettings = observer(() => {
}

if (city) {
// Checks if the city is already added, and if it is a reverse geocoded city.
// If it is not a reverse geocoded city, we can compare by id,
// but if it is a reverse geocoded city, we have to compare by name.
const existingCity = addedCities$
.get()
.find(
(value: ICity) =>
value.name === city.name &&
(value.id.toString().length > 15 || city.id.toString().length > 15),
);
if (addedCities$.get().find((value: ICity) => value.id === city.id)) {
activeCity$.set(city);
toast.success(translationLocationSettings("switched to city toast"));
} else if (existingCity) {
activeCity$.set(existingCity);
toast.success(translationLocationSettings("switched to city toast"));
} else {
addedCities$.push(city);
activeCity$.set(city);
Expand Down Expand Up @@ -379,8 +358,16 @@ const LocationSettings = observer(() => {
const latitude = position.coords.latitude;
const longitude = position.coords.longitude;

findCityByCoordinatesMutation.mutate({
coordinates: { lat: latitude, lng: longitude },
void findCityByCoordinatesMutation({
coord: { lat: latitude, lng: longitude },
}).then((data) => {
if (data) {
setSearchValue(data);
} else {
toast.error(
translationLocationSettings("city not found toast"),
);
}
});
});
}
Expand Down
34 changes: 17 additions & 17 deletions apps/web/src/pages/search/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import Head from "next/head";
import Image from "next/image";
import { useRouter } from "next/router";
import clsx from "clsx";
import { useQuery } from "convex/react";
import { useMutation, useQuery } from "convex/react";
import { ClipLoader } from "react-spinners";
import { toast } from "sonner";

Expand All @@ -13,7 +13,6 @@ import { api as convexApi } from "@weatherio/city-data";

import background from "~/assets/background.png";
import search1Image from "~/assets/search1.png";
import { api as tRPCApi } from "~/lib/utils/api";
import { getLocaleProps, useScopedI18n } from "~/locales";
import { activeCity$, addedCities$ } from "~/states";

Expand Down Expand Up @@ -49,16 +48,9 @@ const Search = () => {
id: searchValue.id,
});

const findCityByCoordinatesMutation =
tRPCApi.reverseGeoRouter.getCity.useMutation({
onSuccess: (data) => {
if (data) {
setSearchValue(data);
} else {
toast.error(translationLocationSettings("city not found toast"));
}
},
});
const findCityByCoordinatesMutation = useMutation(
convexApi.getCity.findNearestCityByCoord,
);

useEffect(() => {
if (searchValue.name === "") {
Expand Down Expand Up @@ -154,14 +146,14 @@ const Search = () => {
.find((value: ICity) => value.name === city.name);
if (addedCities$.get().find((value: ICity) => value.id === city.id)) {
activeCity$.set(city);
void router.push("/home");
void router.push("/home?cityId=" + city.id);
} else if (existingCity) {
activeCity$.set(existingCity);
void router.push("/home");
void router.push("/home?cityId=" + city.id);
} else {
addedCities$.push(city);
activeCity$.set(city);
void router.push("/home");
void router.push("/home?cityId=" + city.id);
}
} else {
toast.error(translationLocationSettings("city not found toast"));
Expand Down Expand Up @@ -312,8 +304,16 @@ const Search = () => {
const latitude = position.coords.latitude;
const longitude = position.coords.longitude;

findCityByCoordinatesMutation.mutate({
coordinates: { lat: latitude, lng: longitude },
void findCityByCoordinatesMutation({
coord: { lat: latitude, lng: longitude },
}).then((data) => {
if (data) {
setSearchValue(data);
} else {
toast.error(
translationLocationSettings("city not found toast"),
);
}
});
});
}
Expand Down
Loading

0 comments on commit b64e644

Please sign in to comment.