Next.js Discord

Discord Forum

Re-render Page on new Data

Unanswered
Sun bear posted this in #help-forum
Open in Discord
Sun bearOP
Hey Guys,

What is the way to go in Next.js when you fetch Data from your Database and display it on the screen and you want to refresh the List when new Data is written to the Database.

I have a game that is showing Game Scores on a Scoreboard. Whenever a new score is written into the database, the scoreboard should refresh to show who is on 1st 2nd or 3rd place. When i write a new score to the database, it arrives there, but the Page doesn't show it until the fetch is run again.

async function getScores() {
  try {
    const res = await fetch("http://localhost:3000/api/scores");

    if (!res.ok) {
      throw new Error(`HTTP error! Status: ${res.status}`);
    }

    const data: Score[] = await res.json();

    if (data.length === 0) {
      throw new Error("No Scores");
    }
    return data;
  } catch (error: any) {
    console.error("Error fetching scores:", error.message);
    throw error;
  }
}


I'm using Route Handlers

export async function GET() {
  const scores = await prisma.gameScore.findMany({
    orderBy: {
      score: "desc",
    },
  });
  console.log(scores);
  return Response.json(scores);
}

Thanks!

12 Replies

@Sun bear Hey Guys, What is the way to go in Next.js when you fetch Data from your Database and display it on the screen and you want to refresh the List when new Data is written to the Database. I have a game that is showing Game Scores on a Scoreboard. Whenever a new score is written into the database, the scoreboard should refresh to show who is on 1st 2nd or 3rd place. When i write a new score to the database, it arrives there, but the Page doesn't show it until the fetch is run again. javascript async function getScores() { try { const res = await fetch("http://localhost:3000/api/scores"); if (!res.ok) { throw new Error(`HTTP error! Status: ${res.status}`); } const data: Score[] = await res.json(); if (data.length === 0) { throw new Error("No Scores"); } return data; } catch (error: any) { console.error("Error fetching scores:", error.message); throw error; } } I'm using Route Handlers javascript export async function GET() { const scores = await prisma.gameScore.findMany({ orderBy: { score: "desc", }, }); console.log(scores); return Response.json(scores); } Thanks!
you can do it with server component
export default async function Page() {
  const scores = await prisma.gameScore.findMany({
    orderBy: {
      score: "desc",
    },
  });

  function add(formData: FormData) {
    'use server'

    await prisma.gameScore.create({
      data: {
        score: formData.get('score')
      }
    })
    
    revalidatePath('/scores')
  }

  return (
    <div>
      {scores.map(score => (
        <div>{score}</div>
      ))}

      <form action={add}>
        <input type="text" name="score" />
        <button>Add</button>
      </form>
    </div>
  )
}
oh then you need something refetch the data every min or so on the page
or sse/websocket
Sun bearOP
Is there a way to refetch in a time interval ? And what is the concept called you provided in your solution so that i can read in more detail about it.
sse and websocket will need a server to publish the event
@Ray you can use swr or react-query for refetch the data in a time interval
Sun bearOP
Websocket is for client <-> server communication. Considering that my fetch is running in a server component, I dont really need communication to the client, do I?
@Sun bear Websocket is for client <-> server communication. Considering that my fetch is running in a server component, I dont really need communication to the client, do I?
1, your web subscribe to your websocket server.
2, POST request to your server and the server update in database then publish the event
Sun bearOP
Oh well I think I will try SWR as it seems to be the right solution
Thank you
yes it easily