Skip to content

Commit

Permalink
update with v3
Browse files Browse the repository at this point in the history
  • Loading branch information
anemne committed Sep 19, 2024
2 parents 3f5fb55 + 52fdfa9 commit 2b9aa46
Show file tree
Hide file tree
Showing 33 changed files with 156 additions and 317 deletions.
1 change: 0 additions & 1 deletion .eslintrc.cjs
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,6 @@ module.exports = {
},
},
rules: {
"@typescript-eslint/no-explicit-any": "off", // TODO
"unused-imports/no-unused-imports": "error",
"import/no-named-as-default": "off",
"import/no-unresolved": "error",
Expand Down
52 changes: 28 additions & 24 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -147,41 +147,45 @@ When building custom components in Sanity Studio that need to fetch data, it's i

**Implementation Example:**

```typescript
```tsx
import React, { useEffect, useState } from "react";
import { fetchWithToken } from "studio/lib/fetchWithToken";

const MyCustomComponent: React.FC = () => {
const [data, setData] = useState<any>(null);
const [error, setError] = useState<string | null>(null);

useEffect(() => {
const fetchData = async () => {
try {
const query = '*[_type == "myType"]'; // Replace with your GROQ query
const result = await fetchWithToken<any>(query);
setData(result);
} catch (err) {
console.error("Error fetching data:", err);
setError(err.message);
}
};

fetchData();
}, []);

if (error) {
return <div>Error: {error}</div>;
}

return <div>{JSON.stringify(data)}</div>; // Render your component's UI
const [data, setData] = useState<any>(null);
const [error, setError] = useState<string | null>(null);

useEffect(() => {
const fetchData = async () => {
try {
const query = '*[_type == "myType"]'; // Replace with your GROQ query
const result = await fetchWithToken<any>(query);
setData(result);
} catch (err) {
console.error("Error fetching data:", err);
setError(err.message);
}
};

fetchData();
}, []);

if (error) {
return <div>Error: {error}</div>;
}

return <div>{JSON.stringify(data)}</div>; // Render your component's UI
};

export default MyCustomComponent;
```

By using fetchWithToken, you ensure that all data fetching happens securely, with the server-side API route handling the sensitive token.

### Steganography in Presentation

To enable preview functionality in the Presentation view, Sanity applies [steganography](https://www.sanity.io/docs/stega) to the string data. This manipulates the data to include invisible HTML entities to store various metadata. If the strings are used in business logic, that logic will likely break in the Presentation view. To fix this, Sanity provides the `stegaClean` utility to remove this extra metadata. An example of this in action can be found in [CompensationsPreview.tsx](src/compensations/CompensationsPreview.tsx), where JSON parsing of salary data fails without stega cleaning.

### OpenGraph image customization

As part of providing the basic metadata for the [OpenGraph Protocol](https://ogp.me), a fallback image is generated if no other is specified. Fonts and background can be customized as shown below.
Expand Down
112 changes: 0 additions & 112 deletions public/headerAnimation.svg

This file was deleted.

2 changes: 1 addition & 1 deletion src/app/(main)/layout.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ import { loadStudioQuery } from "studio/lib/store";

import styles from "./layout.module.css";

const hasValidData = (data: any) => data && Object.keys(data).length > 0;
const hasValidData = (data: unknown) => data && Object.keys(data).length > 0;

export default async function Layout({
children,
Expand Down
2 changes: 1 addition & 1 deletion src/app/api/fetchData/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ const clientWithToken = client.withConfig({ token });

interface FetchRequestBody {
query: string;
params?: Record<string, any>;
params?: Record<string, unknown>;
}

export async function POST(req: Request) {
Expand Down
10 changes: 8 additions & 2 deletions src/blog/components/legal/Legal.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import Link from "next/link";
import { PortableTextBlock } from "sanity";

import { PortableTextBlock, RichText } from "src/components/richText/RichText";
import { RichText } from "src/components/richText/RichText";
import Text from "src/components/text/Text";
import { LegalDocument } from "studio/lib/interfaces/legalDocuments";

Expand All @@ -9,7 +10,12 @@ import styles from "./legal.module.css";
const extractHeadings = (blocks: PortableTextBlock[]) => {
return blocks
.filter((block) => block.style === "h2")
.map((block) => block.children?.map((child) => child.text).join(" ") || "");
.map(
(block) =>
(Array.isArray(block.children) &&
block.children?.map((child) => child.text).join(" ")) ||
"",
);
};

const Legal = ({ document }: { document: LegalDocument }) => {
Expand Down
16 changes: 13 additions & 3 deletions src/blog/components/postPreview/PostPreview.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
"use client";
import { PortableTextBlock } from "sanity";

import CustomLink from "src/components/link/CustomLink";
import { PortableTextBlock, RichText } from "src/components/richText/RichText";
import { RichText } from "src/components/richText/RichText";
import Text from "src/components/text/Text";
import { useConvertSanityImageToNextImage } from "src/utils/hooks/useConvertImage";
import { LinkType } from "studio/lib/interfaces/navigation";
Expand Down Expand Up @@ -32,12 +34,20 @@ const PostPreview = ({
},
};

const truncateFirstBlock = (richText: PortableTextBlock[], limit: number) => {
const truncateFirstBlock = (
richText: PortableTextBlock[],
limit: number,
): PortableTextBlock[] => {
if (!richText || richText.length === 0) return richText;

const firstBlock = richText[0];
let charCount = 0;
const truncatedChildren = firstBlock?.children?.map((child) => {

if (!("children" in firstBlock) || !Array.isArray(firstBlock.children)) {
return [firstBlock];
}

const truncatedChildren = firstBlock.children?.map((child) => {
if (charCount >= limit) return { ...child, text: "" };
const remainingChars = limit - charCount;
const truncatedText = child.text.slice(0, remainingChars);
Expand Down
3 changes: 2 additions & 1 deletion src/blog/components/postPreview/mockData.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { PortableTextBlock } from "src/components/richText/RichText";
import { PortableTextBlock } from "sanity";

import placeholder from "src/stories/assets/image-placeholder.png";

// Common rich text for lead and main content
Expand Down
9 changes: 7 additions & 2 deletions src/compensations/CompensationsPreview.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
"use client";
import { stegaClean } from "@sanity/client/stega";
import { QueryResponseInitial, useQuery } from "@sanity/react-loader";
import { Suspense } from "react";

Expand All @@ -18,7 +19,7 @@ const CompensationsPreview = ({
initialCompensations,
initialLocations,
}: CompensationsPreviewProps) => {
const { data: compensationData } = useQuery<CompensationsPage>(
const { data: compensationsData } = useQuery<CompensationsPage>(
COMPENSATIONS_PAGE_QUERY,
{ slug: initialCompensations.data.slug.current },
{ initial: initialCompensations },
Expand All @@ -29,11 +30,15 @@ const CompensationsPreview = ({
{ initial: initialLocations },
);

compensationsData.salariesByLocation = stegaClean(
compensationsData.salariesByLocation,
);

return (
locationData && (
<Suspense>
<Compensations
compensations={compensationData}
compensations={compensationsData}
locations={locationData}
/>
</Suspense>
Expand Down
2 changes: 1 addition & 1 deletion src/components/forms/checkbox/Checkbox.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { PortableText } from "@portabletext/react";
import { PortableTextBlock } from "sanity";

import { PortableTextBlock } from "src/components/richText/RichText";
import Text from "src/components/text/Text";
import textStyles from "src/components/text/text.module.css";

Expand Down
Loading

0 comments on commit 2b9aa46

Please sign in to comment.