Skip to content

Commit

Permalink
Normalize country codes only on server (fixes #72)
Browse files Browse the repository at this point in the history
  • Loading branch information
benvinegar committed Apr 16, 2024
1 parent faea104 commit d0575fe
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 36 deletions.
37 changes: 4 additions & 33 deletions app/routes/dashboard.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -207,7 +207,7 @@ describe("Dashboard route", () => {
visits: 3,
visitors: 1,
countByPath: [["/", 1, 4]],
countByCountry: [["US", 1]],
countByCountry: [["United States", 1]],
countByReferrer: [["google.com", 1]],
countByBrowser: [["Chrome", 2]],
countByDevice: [["Desktop", 3]],
Expand Down Expand Up @@ -331,9 +331,9 @@ describe("Dashboard route", () => {
["Firefox", 60],
],
countByCountry: [
["US", 100],
["CA", 80],
["UK", 60],
["United States", 100],
["Canada", 80],
["United Kingdom", 60],
],
countByReferrer: [
["google.com", 100],
Expand Down Expand Up @@ -386,33 +386,4 @@ describe("Dashboard route", () => {
expect(screen.getByText("Canada")).toBeInTheDocument(); // assert converted CA -> Canada
expect(screen.getByText("Mobile")).toBeInTheDocument();
});

test("renders with invalid country code", async () => {
function loader() {
return json({
...defaultMockedLoaderJson,
countByCountry: [
["US", 100],
["CA", 80],
["not_a_valid_country_code", 60],
],
});
}

const RemixStub = createRemixStub([
{
path: "/",
Component: Dashboard,
loader,
},
]);

render(<RemixStub />);

// wait until the rows render in the document
await waitFor(() => screen.findByText("Chrome"));

// assert the invalid country code was converted to "(unknown)"
expect(screen.getByText("(unknown)")).toBeInTheDocument();
});
});
11 changes: 8 additions & 3 deletions app/routes/dashboard.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -178,6 +178,13 @@ export const loader = async ({ context, request }: LoaderFunctionArgs) => {
console.error(err);
throw new Error("Failed to fetch data from Analytics Engine");
}

// normalize country codes to country names
// NOTE: this must be done ONLY on server otherwise hydration mismatches
// can occur because Intl.DisplayNames produces different results
// in different browsers (see )
out.countByCountry = convertCountryCodesToNames(out.countByCountry);

return json(out);
};

Expand Down Expand Up @@ -229,8 +236,6 @@ export default function Dashboard() {
});
});

const countByCountryName = convertCountryCodesToNames(data.countByCountry);

const countFormatter = Intl.NumberFormat("en", { notation: "compact" });

return (
Expand Down Expand Up @@ -338,7 +343,7 @@ export default function Dashboard() {
columnHeaders={["Browser", "Visitors"]}
/>
<TableCard
countByProperty={countByCountryName}
countByProperty={data.countByCountry}
columnHeaders={["Country", "Visitors"]}
/>
<TableCard
Expand Down

0 comments on commit d0575fe

Please sign in to comment.