Next.js Discord

Discord Forum

Fetch fail after few refreshes

Unanswered
Giant Angora posted this in #help-forum
Open in Discord
Giant AngoraOP
Hello , i have a next.js project , and in one of its pages , there's too much fetch requests to get data from next.js api , when i run it on production server , it call all of them , but after an refresh , it wont call some of them :

41 Replies

@Giant Angora https://gist.github.com/ThisIsTheMatin/3ac9725f18c44f57cf27e72d0d7cfba2
Giant AngoraOP
Console content , if you check , it will return all of fetches in first page refresh , then it just fetch some of them , and after that it wont fetch anything until you restart server
@Anay-208 | Ping in replies
@West African Lion
Need your help 😅 ❤️
Giant AngoraOP
No
I disabled it since you told me
Cause it make too much problems for my fetch requests
I'm currently busy working in the hackathon. You can wait for someone else to respond or ping me on 18th
@Anay-208 | Ping in replies I'm currently busy working in the hackathon. You can wait for someone else to respond or ping me on 18th
Giant AngoraOP
Oh sure!
I mean if you could just give a few minutes to help for this to solve ❤️
But if you couldn't , its ok (:
Even if its a few mins problem, It'd take me much longer time because we've less time left to refine everything.

For instance, one of my team members weren't able to solve a bug, which took me few mins to solve(since I was done with my tasks and had some extra time before winding up for the day)
Giant AngoraOP
@Anay-208 | Ping in replies Hello
can you provide a minimum reproductive repo
Giant AngoraOP
I can provide my problem for you in one chat
export default function DashboardPage() {

    const [profeData, setProfeData] = useState({});
    const [profeSubscription, setProfeSubscription] = useState({})
    const [profeConnections, setProfeConnections] = useState({})
    const [profeTheme, setProfeTheme] = useState({})
    const [loaded, setLoaded] = useState(false);
  
    useEffect(() => {
      if (!localStorage.getItem("profe_token")) {
        window.location.href = "/connect"
      }
    },[])

    useEffect(() => {
        setLoaded(false)
        const fetchData = async () => {
          
            const profe_token = localStorage.getItem("profe_token");
            
            if (profe_token) {
              const getDashboardDataRequest = await fetch("/api/dashboard/get", {
                method: "POST",
                cache: "no-store",
                next: {
                  revalidate: 0,

                },
                headers: {
                    "Content-Type": "application/json"
                },
                body: JSON.stringify({ token: profe_token }),
              });
              
              const getDashboardDataResponse = await getDashboardDataRequest.json();
              
              if (getDashboardDataResponse && getDashboardDataResponse.result == "ok") {
                setProfeData(getDashboardDataResponse.data.profeData)
                setProfeSubscription(getDashboardDataResponse.data.profeSubscription)
                setProfeConnections(getDashboardDataResponse.data.profeConnections)
                setProfeTheme(getDashboardDataResponse.data.profeTheme)
                setLoaded(true)
                
              }

              }
              else {
                localStorage.removeItem("profe_token")
                window.location.href = "/connect"
              }

            }
        fetchData();
    }, []);


/app/dashboard/page.js
import { NextResponse } from "next/server";
import pool from "../../database";
import db from "@/app/api/database";

export async function POST(req) {
    const body = await req.json();
    const { token } = body;

    await db.connect();
    let query;
    let result;

    let profeData;
    let profeSubscription;
    let profeConnections;
    let profeTheme;

    console.log("Calling Dashboard Get Data Route");
    

    query = await db.query("SELECT user_id FROM users WHERE user_token = $1",[token]);
    result = query.rows[0];

    console.log("Getting User Query",result);
    

    if (result && result.user_id) {
        
        const user_id = result.user_id
        query = await db.query("SELECT profe_id,profe_creator,profe_handle,profe_displayname,profe_email,profe_job,profe_bio,profe_theme,profe_subscription,profe_state,profe_havepfp,profe_havepfb FROM profes WHERE profe_creator = $1",[user_id])
        result = query.rows[0];

        if (result && result.profe_id) {
            profeData = {
                result: "ok",
                data: result,
                action: "get_profe"
            }

            // GET PROFE SUBSCRIPTION
            query = await db.query("SELECT sub_id,sub_owner,sub_tier,sub_method,sub_is_unlimited,sub_duration,sub_state,sub_creation_date,sub_expire_date,sub_is_gifted,sub_gifted_by,sub_gift_reason,sub_is_expired FROM subscriptions WHERE sub_owner = $1",[profeData.data.profe_id])
            result = query.rows[0]
            if (result && result.sub_id && result.sub_is_expired == false) {
                profeSubscription = {
                    result: "ok",
                    data: result,
                    action: "get_profe_subscription"
                }
            }
            else {
                profeSubscription = {
                    result: "fail",
                    action: "get_profe_subscription"
                }

            }

/api/dashboard/get/route.js ( part 1 )
import { NextResponse } from "next/server";
import pool from "../../database";
import db from "@/app/api/database";

export async function POST(req) {
    const body = await req.json();
    const { token } = body;

    await db.connect();
    let query;
    let result;

    let profeData;
    let profeSubscription;
    let profeConnections;
    let profeTheme;

    console.log("Calling Dashboard Get Data Route");
    

    query = await db.query("SELECT user_id FROM users WHERE user_token = $1",[token]);
    result = query.rows[0];

    console.log("Getting User Query",result);
    

    if (result && result.user_id) {
        
        const user_id = result.user_id
        query = await db.query("SELECT profe_id,profe_creator,profe_handle,profe_displayname,profe_email,profe_job,profe_bio,profe_theme,profe_subscription,profe_state,profe_havepfp,profe_havepfb FROM profes WHERE profe_creator = $1",[user_id])
        result = query.rows[0];

        if (result && result.profe_id) {
            profeData = {
                result: "ok",
                data: result,
                action: "get_profe"
            }

            // GET PROFE SUBSCRIPTION
            query = await db.query("SELECT sub_id,sub_owner,sub_tier,sub_method,sub_is_unlimited,sub_duration,sub_state,sub_creation_date,sub_expire_date,sub_is_gifted,sub_gifted_by,sub_gift_reason,sub_is_expired FROM subscriptions WHERE sub_owner = $1",[profeData.data.profe_id])
            result = query.rows[0]
            if (result && result.sub_id && result.sub_is_expired == false) {
                profeSubscription = {
                    result: "ok",
                    data: result,
                    action: "get_profe_subscription"
                }
            }
            else {
                profeSubscription = {
                    result: "fail",
                    action: "get_profe_subscription"
                }

            }

            

/api/dashboard/get/route.js ( part 2 )
@Giant Angora js export default function DashboardPage() { const [profeData, setProfeData] = useState({}); const [profeSubscription, setProfeSubscription] = useState({}) const [profeConnections, setProfeConnections] = useState({}) const [profeTheme, setProfeTheme] = useState({}) const [loaded, setLoaded] = useState(false); useEffect(() => { if (!localStorage.getItem("profe_token")) { window.location.href = "/connect" } },[]) useEffect(() => { setLoaded(false) const fetchData = async () => { const profe_token = localStorage.getItem("profe_token"); if (profe_token) { const getDashboardDataRequest = await fetch("/api/dashboard/get", { method: "POST", cache: "no-store", next: { revalidate: 0, }, headers: { "Content-Type": "application/json" }, body: JSON.stringify({ token: profe_token }), }); const getDashboardDataResponse = await getDashboardDataRequest.json(); if (getDashboardDataResponse && getDashboardDataResponse.result == "ok") { setProfeData(getDashboardDataResponse.data.profeData) setProfeSubscription(getDashboardDataResponse.data.profeSubscription) setProfeConnections(getDashboardDataResponse.data.profeConnections) setProfeTheme(getDashboardDataResponse.data.profeTheme) setLoaded(true) } } else { localStorage.removeItem("profe_token") window.location.href = "/connect" } } fetchData(); }, []); /app/dashboard/page.js
Giant AngoraOP
Here , when user go to /dashboard , it will check if user have profe_token cookie in his browser cookies , and based of cookie , it call an route ( /api/dashboard/get ) to get user based of cookie in users table with query , and based of availability of user , it will get other related things for user and return all of them in one object
Now , my problem is when i load /dashboard page , it will successfully do fetch call and return needed things
Then , when i refresh page or navigate between dashboard pages , it still call api successfully
After that , still calling api successfully , but...
When i refresh page again , call get stuck on Pending and it will get stuck in receiving data
[Error: read ECONNRESET] {
  errno: -4077,
  code: 'ECONNRESET',
  syscall: 'read'
}
 ⨯ uncaughtException:  [Error: read ECONNRESET] {
  errno: -4077,
  code: 'ECONNRESET',
  syscall: 'read'
}
[Error: Connection terminated unexpectedly]
 ⨯ uncaughtException:  [Error: Connection terminated unexpectedly]
[Error: Connection terminated unexpectedly]
 ⨯ uncaughtException:  [Error: Connection terminated unexpectedly]
[Error: read ECONNRESET] {
  errno: -4077,
  code: 'ECONNRESET',
  syscall: 'read'
}
 ⨯ uncaughtException:  [Error: read ECONNRESET] {
  errno: -4077,
  code: 'ECONNRESET',
  syscall: 'read'
}
[Error: Connection terminated unexpectedly]
 ⨯ uncaughtException:  [Error: Connection terminated unexpectedly]
[Error: Connection terminated unexpectedly]
 ⨯ uncaughtException:  [Error: Connection terminated unexpectedly]
That's my currently problem
I don't know i guess there's a connection limit , rate limit or something else that wont let me to do more queries in period of time...
@Anay-208 | Ping in replies
Let me see
Giant AngoraOP
Thanks
Giant AngoraOP
Also , im using Supabase for database management
or wsl?
@Anay-208 | Ping in replies Are you using Github Codespace as dev environment?
Giant AngoraOP
Nope , next.js dev on my client pc
I can't help with this without a minimum reproducible repo
Giant AngoraOP
So how can i pass envoirment things like database connection credentials
Also, some general tips which I'd give:
- Use a ORM or query builder like Drizzle or kysely
- If its your usecase, you can return early in if statements
just give us a command to create schemas
and mention env Variables to be added in README.md

I can set it up locally
Giant AngoraOP
Lemme see
Once you give, I'll be able to check it tmr