superhuit-agency / superstack

Our opinionated headless WordPress boilerplate - with GraphQL, RSC, PostCSS
MIT License
24 stars 4 forks source link

Improve getData #28

Closed kuuak closed 3 months ago

kuuak commented 3 months ago

While reading about Faustjs, I saw a simple snippet which caught my eye.

Capture d’écran 2024-07-23 à 14 12 51

The fact to expose the graphql query from the component, the same way we expose the slug and title from the component is quite neat.

I suggest to adapt the stack to expose the getData function directly from the component.

Find below the few changes we would need to do (not exaustive).

diff --git a/src/typings.d.ts b/src/typings.d.ts
--- a/src/typings.d.ts
+++ b/src/typings.d.ts
@@ -73,9 +73,18 @@ export type VideoProps = Omit<HTMLProps<HTMLVideoElement>, 'poster'> & {
    url?: string;
 };

-export type BlockConfigs = {
+interface GetDataFuncType<T> {
+   (
+       fetcher: FetchApiFuncType,
+       attrs: any,
+       isEditor: boolean
+   ): Promise<T>;
+}
+
+interface BlockConfigs {
    slug?: string;
    title?: string;
+   getData?: GetDataFuncType;
 };

 export type MenuItemType = LinkProps & {
diff --git a/src/components/organisms/sections/SectionNews/index.tsx b/src/components/organisms/sections/SectionNews/index.tsx
--- a/src/components/organisms/sections/SectionNews/index.tsx
+++ b/src/components/organisms/sections/SectionNews/index.tsx
@@ -10,25 +10,26 @@ import block from './block.json';

 // styles
 import './styles.css';
+import { getData } from './data';

 /**
  * TYPINGS
  */
-
-export interface SectionNewsPost {
-   posts: Array<CardNewsProps>;
-}
-
-export interface SectionNewsProps extends SectionNewsPost, SectionProps {
+interface SectionNewsAttributes {
    seeAllLink: LinkProps;
    postLinkLabel?: string;
    queryVars?: Record<string, any>;
 }
+export interface SectionNewsData {
+   posts: Array<CardNewsProps>;
+}
+
+interface SectionNewsProps extends SectionNewsAttributes, SectionNewsData, SectionProps {}

 /**
  * COMPONENT
  */
-export const SectionNews: FC<SectionNewsProps> & BlockConfigs = ({
+export const SectionNews: FC<SectionNewsProps> & BlockConfigs<SectionNewsData> = ({
    anchor,
    className,
    uptitle,
@@ -80,3 +81,4 @@ export const SectionNews: FC<SectionNewsProps> & BlockConfigs = ({

 SectionNews.slug = block.slug;
 SectionNews.title = block.title;
+SectionNews.getData = getData;

I would mean that we do not need to have a data.ts file to import/re-export all data functions.

Maybe it would be also interresting to have a .data which regroup all getData, formatter, fragment or any other exported function/string from the data.tsx file

kuuak commented 3 months ago

After discussion we won't do this change as it would mean that the getData code would be shipped to the front-end component.