Dynamic blog rendering for regular react/typescript app

Hi @cedson, Hope you are doing well!

Let’s go through your code to understand the issue and ensure it is configured correctly for fetching and rendering specific blog posts dynamically with React and TypeScript in a Builder.io environment.

Step-by-Step Debugging and Fixing:

  1. Initialization and Configuration:

    • Ensure Builder.io SDK is initialized with the correct public API key.
    • Double-check that the correct content models are being queried (article and blog-template).
  2. Slug Matching:

    • Ensure the slug used in your URL matches the slug used in the Builder.io data model.
  3. API Query and Response:

    • Verify that the response data contains the expected fields and is correctly parsed.

Example Improvements and Validation:

Complete and Improved Example:

import React, { useEffect, useState } from 'react';
import { useParams } from 'react-router-dom';
import { BuilderComponent, builder, useIsPreviewing } from '@builder.io/react';
import styles from './blog.module.css';

builder.init('YOUR_PUBLIC_API_KEY');

interface ArticleData {
  data: {
    slug: string;
    title: string;
    // Add any other fields your article content model contains
    content: any;
  };
}

interface ArticleTemplate {
  data: any; // Replace with the specific type based on your template's data structure
}

export function Blog() {
  const { slug } = useParams<{ slug: string }>();
  const isPreviewingInBuilder = useIsPreviewing();
  const [notFound, setNotFound] = useState(false);
  const [articleData, setArticleData] = useState<ArticleData | null>(null);
  const [articleTemplate, setArticleTemplate] = useState<ArticleTemplate | null>(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    async function fetchContent() {
      try {
        // Fetch the specific article by slug
        const articleResponse = await builder
          .get('article', {
            options: { includeRefs: true },
            query: {
              'data.slug': slug,
            },
          })
          .toPromise();
        console.log('Article Response:', articleResponse);

        // Fetch the blog template
        const templateResponse = await builder
          .get('blog-template', {
            options: { enrich: true },
          })
          .toPromise();
        console.log('Template Response:', templateResponse);

        if (articleResponse && articleResponse.length > 0 && templateResponse) {
          setArticleData(articleResponse[0]);
          setArticleTemplate(templateResponse);
        } else {
          setNotFound(true);
        }
      } catch (error) {
        console.error('Error fetching data:', error);
        setNotFound(true);
      } finally {
        setLoading(false);
      }
    }

    fetchContent();
  }, [slug]);

  if (loading) {
    return <h1>Loading...</h1>;
  }

  if (notFound && !isPreviewingInBuilder) {
    return <div>Not Found 404 Error</div>;
  }

  return (
    <div className={styles.container}>
      <meta name="viewport" content="width=device-width, initial-scale=1" />
      {!articleData && <meta name="robots" content="noindex" />}
      {articleData && articleTemplate && (
        <BuilderComponent
          model="blog-template"
          content={articleTemplate}
          data={{ article: articleData.data }}
        />
      )}
    </div>
  );
};

Key Points to Note:

  1. Initialization:

    • Ensure builder.init('YOUR_PUBLIC_API_KEY') uses the correct API key.
  2. Slug Matching and Query:

    • The slug used in the URL must match the slug field in your Builder.io model.
    • Ensure the data.slug key matches how your slug is stored in Builder.io.
  3. Check Network Requests:

    • Use the browser’s network tab to check the actual API requests being made.
    • Look at the query parameters and response to ensure they match your expectations.
  4. Handling Responses:

    • Ensure articleResponse and templateResponse are correctly checked.
    • Use appropriate checks to handle arrays or single objects based on your API response structure.
  5. Error Handling and Debugging:

    • Add console statements like console.log to check intermediate steps and responses.

Testing and Debugging:

  1. Network Tab:

    • Open Developer Tools (F12) and check the network tab.
    • Look at the requests to Builder.io and ensure the correct data is being fetched.
  2. Console Logging:

    • Use console.log extensively to debug and ensure the data fetching is working correctly:
      console.log('Article Response:', articleResponse);
      console.log('Template Response:', templateResponse);
      

By following these steps and ensuring the data fetched is correctly handled and matched to your expected structure, you should be able to get the blog posts to display correctly. If issues persist, dive deeper into the responses in the network tab and adjust the query or data parsing as necessary.