Skip to content

Commit

Permalink
pat page startup
Browse files Browse the repository at this point in the history
  • Loading branch information
docimin committed Nov 10, 2023
1 parent a64baa8 commit 74a05ed
Show file tree
Hide file tree
Showing 4 changed files with 149 additions and 2 deletions.
34 changes: 34 additions & 0 deletions app/api/fun/pats/[uniqueId]/route.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
import { NextResponse } from "next/server";

export const runtime = "edge";

export async function GET(request) {
try {
// Assume the last segment of the URL is the user ID
const userId = request.url.split("/").pop();

// Construct the URL for the external fetch
const fetchURL = `${process.env.NEXT_PUBLIC_DOMAIN_API}/api/pats?filters[users_permissions_user]=${userId}]`;

const response = await fetch(fetchURL, {
method: "GET",
headers: {
Authorization: `Bearer ${process.env.DOMAIN_API_KEY}`,
"Content-Type": "application/json",
},
});

if (!response.ok) {
throw new Error("Failed to fetch data");
}

const data = await response.json();
return NextResponse.json(data, { status: 200 });
} catch (error) {
console.error(error);
return NextResponse.json(
{ error: "Internal Server Error" },
{ status: 500 }
);
}
}
30 changes: 30 additions & 0 deletions app/api/fun/pats/create/route.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
import { NextResponse } from "next/server";

export const runtime = "edge";

export async function POST(request) {
try {
const requestBody = await request.json();

// Construct the URL for the external fetch
const fetchURL = `${process.env.NEXT_PUBLIC_DOMAIN_API}/api/pats`;

const response = await fetch(fetchURL, {
method: "POST",
headers: {
Authorization: `Bearer ${process.env.DOMAIN_API_KEY}`,
"Content-Type": "application/json",
},
body: JSON.stringify(requestBody),
});

if (!response.ok) {
throw new Error("Failed to update data");
}

const data = await response.json();
return NextResponse.json(data, { status: 200 });
} catch (error) {
return NextResponse.json(error.message, { status: 500 });
}
}
86 changes: 84 additions & 2 deletions app/pat/page.jsx
Original file line number Diff line number Diff line change
@@ -1,9 +1,91 @@

"use client";
import { useEffect, useState } from "react";

export default function Home() {
const [userId, setUserId] = useState(null);
const [patCount, setPatCount] = useState(null);

useEffect(() => {
const fetchData = async () => {
try {
// Check if JWT cookie exists
const jwtCookie = document.cookie.replace(
/(?:(?:^|.*;\s*)jwt\s*=\s*([^;]*).*$)|^.*$/,
"$1"
);
if (!jwtCookie || userId) {
// If JWT cookie doesn't exist or data has already been fetched, return
return;
}

// Fetch user data
const userResponse = await fetch("/api/user/getUserSelf", {
method: "GET",
});
const userData = await userResponse.json();

if (!userData) {
return;
}

// Extract user ID
const { id } = userData;

// Fetch pat count using user ID
const patResponse = await fetch(`/api/fun/pats/${id}`, {
method: "GET",
});

// Check if the data array is null or empty
const patData = await patResponse.json();

if (patData.data && patData.data.length === 0) {
// Make a POST request to create data if no records are found
console.log("Creating pat count data");
await fetch("/api/fun/pats/create", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
data: {
users_permissions_user: id,
},
}),
});
}

// Fetch pat count again
console.log("Fetching updated pat count data");
const updatedPatResponse = await fetch(`/api/fun/pats/${id}`, {
headers: {
Authorization: `Bearer ${jwtCookie}`,
},
});
const updatedPatData = await updatedPatResponse.json();

// Extract pat count
const count = updatedPatData?.data[0]?.attributes?.count;

// Update state
console.log("Before setting userId:", userId);

setUserId(id);
console.log("Before setting userId:", userId);

setPatCount(count);
} catch (error) {
console.error("Error fetching data:", error);
}
};

fetchData();
}, [userId]); // The effect now depends on userId

return (
<>
Click me!
<div>User ID: {userId}</div>
<div>Pat Count: {patCount}</div>
</>
);
}
1 change: 1 addition & 0 deletions next.config.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
/** @type {import('next').NextConfig} */
const nextConfig = {
reactStrictMode: false,
images: {
deviceSizes: [320, 420, 768, 1024, 1200],
loader: "default",
Expand Down

0 comments on commit 74a05ed

Please sign in to comment.