Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

usando nextjs e supabase #2

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
84 changes: 82 additions & 2 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@
"axios": "^0.27.2",
"classnames": "^2.3.1",
"cypress": "^10.1.0",
"date-fns": "^3.3.1",
"gray-matter": "^4.0.2",
"next": "latest",
"next-mdx-remote": "^4.1.0",
Expand Down
4 changes: 2 additions & 2 deletions pages/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import { getGlobalData } from '../utils/global-data';
import SEO from '../components/SEO';

export default function Index({ posts, globalData }) {

return (
<Layout>
<SEO title={globalData.name} description={globalData.blogTitle} />
Expand Down Expand Up @@ -36,7 +37,7 @@ export default function Index({ posts, globalData }) {
<h2 className="text-2xl md:text-3xl">{post.title}</h2>
{post.description && (
<p className="mt-3 text-lg opacity-60">
{post.description}
{post.description}
</p>
)}
<ArrowIcon className="mt-4" />
Expand All @@ -63,6 +64,5 @@ export async function getServerSideProps() {
const posts = await getPosts();
const globalData = getGlobalData()


return { props: { posts, globalData } };
}
73 changes: 51 additions & 22 deletions pages/posts/[id].js
Original file line number Diff line number Diff line change
Expand Up @@ -3,47 +3,75 @@ import {
getPostBySlug,
} from '../../utils/mdx-utils';

import { MDXRemote } from 'next-mdx-remote';
import Head from 'next/head';
import Link from 'next/link';
import ArrowIcon from '../../components/ArrowIcon';
import CustomLink from '../../components/CustomLink';
import Footer from '../../components/Footer';
import Header from '../../components/Header';
import Layout, { GradientBackground } from '../../components/Layout';
import SEO from '../../components/SEO';
import { useRouter } from 'next/router';
import { format } from 'date-fns';


const components = {
a: CustomLink,
Head,
};

export default function PostPage({
posts,
globalData,
}) {
export default function PostPage({ post, globalData }) {
console.log('PostPage - Post:', post);
const router = useRouter();

if (router.isFallback) {
// opcional: adicionar um indicador de carregamento enquanto os dados estão sendo buscados
return <div>Carregando...</div>;

}

const { id, title, body, created_at, user_id } = post[0];

// Supondo que `user` seja a variável que contém os dados do usuário
const { id: userId, name, email } = post[0]?.user || {};

// Agora você pode usar essas variáveis como precisar
console.log("ID do post:", id);
console.log("Título do post:", title);
console.log("Corpo do post:", body);
console.log("Data de criação:", created_at);
console.log("ID do usuário associado ao post:", user_id);
console.log("ID do usuário:", userId);
console.log("Nome do usuário:", name);
console.log("Email do usuário:", email);


const dateFormatt = format(new Date(created_at), 'dd/MM/yyyy')

return (
<Layout>
<SEO
title={`${posts.title} - ${globalData.name}`}
description={posts.description}
title={`${title} - ${globalData.name}`}
description={body}
/>
<Header name={globalData.name} />
<article className="px-6 md:px-0">
<header>
<h1 className="text-3xl md:text-5xl dark:text-white text-center mb-12">
{posts?.title}
{title}
</h1>
{posts?.description && (
<p className="text-xl mb-4">{posts?.description}</p>
{body && (
<p className="text-xl mb-4">{body}</p>
)}
</header>
<main>
<article className="prose dark:prose-dark">
{posts.body}
{user_id}
</article>
</main>
<footer>
<article className="prose dark:prose-dark">
{dateFormatt}
</article>
</footer>
</article>
<Footer copyrightText={globalData.footerText} />
<GradientBackground
Expand All @@ -58,16 +86,17 @@ export default function PostPage({
);
}

export const getServerSideProps = async ({ params }) => {
export async function getServerSideProps({ params }) {
const globalData = getGlobalData();
const posts = await getPostBySlug(params.id);

const post = await getPostBySlug(params.id);

if (!post) {
console.error('Post not found!');
return {
notFound: true,
};
}

return {
props: {
globalData,
posts,
},
};
return { props: { post, globalData } };
};

8 changes: 4 additions & 4 deletions services/api.js
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
import axios from 'axios';

export const api = axios.create({
baseURL: 'https://nuareafrukmnjnaakplk.supabase.co/rest/v1',
export const api = axios.create({
baseURL: 'https://eewkwnyrcutvzbngpsam.supabase.co/rest/v1',
headers: {
apikey: "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6Im51YXJlYWZydWttbmpuYWFrcGxrIiwicm9sZSI6ImFub24iLCJpYXQiOjE2NjAyMjc0MjEsImV4cCI6MTk3NTgwMzQyMX0.3qUEldVsmcr_yrpf8N1-qBGdHLB1QCy9nB6-nApVQIA",
authorization: "Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6Im51YXJlYWZydWttbmpuYWFrcGxrIiwicm9sZSI6ImFub24iLCJpYXQiOjE2NjAyMjc0MjEsImV4cCI6MTk3NTgwMzQyMX0.3qUEldVsmcr_yrpf8N1-qBGdHLB1QCy9nB6-nApVQIA"
apikey: "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6ImVld2t3bnlyY3V0dnpibmdwc2FtIiwicm9sZSI6ImFub24iLCJpYXQiOjE3MDY2MzIyMDUsImV4cCI6MjAyMjIwODIwNX0.ZkPlledIYiVkYgQWnBw1shQ5wim-R_CVqsDbMvm7SaA",
authorization: "Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6ImVld2t3bnlyY3V0dnpibmdwc2FtIiwicm9sZSI6ImFub24iLCJpYXQiOjE3MDY2MzIyMDUsImV4cCI6MjAyMjIwODIwNX0.ZkPlledIYiVkYgQWnBw1shQ5wim-R_CVqsDbMvm7SaA"
}
})
20 changes: 15 additions & 5 deletions utils/mdx-utils.js
Original file line number Diff line number Diff line change
@@ -1,19 +1,29 @@
import { api } from '../services/api'

export const getPosts = async () => {
const {data} = await api.get('/posts');
const { data } = await api.get('/post');

if(data){
if (data) {
return data;
}

return []
}

export const getPostBySlug = async (id) => {
console.log('getPostBySlug - ID:', id);
try {
const { data } = await api.get(`/post?id=eq.${id}`);

//TODO: BUSCAR UM POST EM ESPECIFICO.
//const {data} = await api.get(`/post?id=eq.${id}`)
console.log('getPostBySlug - Data:', data);

return {}
if (!data || data.length === 0) {
return null;
}

return data;
} catch (error) {
console.error(`Error fetching post with ID ${id}:`, error);
return null; // Mudança aqui, retornar null em caso de erro
}
}
Loading