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:
-
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 (
articleandblog-template).
-
Slug Matching:
- Ensure the slug used in your URL matches the slug used in the Builder.io data model.
-
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:
-
Initialization:
- Ensure
builder.init('YOUR_PUBLIC_API_KEY')uses the correct API key.
- Ensure
-
Slug Matching and Query:
- The slug used in the URL must match the
slugfield in your Builder.io model. - Ensure the
data.slugkey matches how your slug is stored in Builder.io.
- The slug used in the URL must match the
-
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.
-
Handling Responses:
- Ensure
articleResponseandtemplateResponseare correctly checked. - Use appropriate checks to handle arrays or single objects based on your API response structure.
- Ensure
-
Error Handling and Debugging:
- Add console statements like
console.logto check intermediate steps and responses.
- Add console statements like
Testing and Debugging:
-
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.
-
Console Logging:
- Use
console.logextensively to debug and ensure the data fetching is working correctly:console.log('Article Response:', articleResponse); console.log('Template Response:', templateResponse);
- Use
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.