Next.js Discord

Discord Forum

Refetch data every 1 second on page

Answered
kkkotiqqq posted this in #help-forum
Open in Discord
Please help i'm new in Next and React
i have page and function

how can i refetch data every 1 sec from wp rest api to update information on page?

async function getTables() {
const res = await fetch(https://site.com/wp-json/wp/v2/pages/17, {
cache: "no-store",
});
return res.json();
}

export default async function Home() {
const tableData = await getTables();
return ()
}
Answered by Northern Wheatear
use SWR
View full answer

31 Replies

Northern Wheatear
Do you want to update the content on your page every 1 sec or on page refresh
@Northern Wheatear Do you want to update the content on your page every 1 sec or on page refresh
i want update content without page refresh by user (by click F5 for example)
that is, the person will open the page and the data will start to be updated without any action on the part of the user
Northern Wheatear
Oh then you need to refetch the data client side also... Refetch it in a loop with setInterval
Now I'm looking towards SWR with Revalidate on Interval option
Northern Wheatear
Thats a better option
@Northern Wheatear Oh then you need to refetch the data client side also... Refetch it in a loop with setInterval
the main thing for me is to make it work 🙂 this page does not need seo or anything like that, it is only necessary that the information is updated as if "in real time" for one person
Northern Wheatear
Then fetch the data using swr with revalidate.... If seo is also important you can send the initial data from server and later on update it with swr and update your components accordingly
@Northern Wheatear Then fetch the data using swr with revalidate.... If seo is also important you can send the initial data from server and later on update it with swr and update your components accordingly
I understand the concept of what needs to be done, but unfortunately there is not enough technical knowledge yet 😦 I will try.

I managed to make a page through the "use client" and update the data using setInterval, but on the page itself I could not normally access the updated data, they were displayed, then they became undefined
@kkkotiqqq I understand the concept of what needs to be done, but unfortunately there is not enough technical knowledge yet 😦 I will try. I managed to make a page through the "use client" and update the data using setInterval, but on the page itself I could not normally access the updated data, they were displayed, then they became undefined
try this
async function getTables() {
  const res = await fetch("https://site.com/wp-json/wp/v2/pages/17", {
    cache: "no-store",
  });
  return res.json();
}

export default async function Home() {
  const tableData = await getTables();
  return <Client tables={tableData} />;
}

// client
'use client'

function Client(props) {
  const [tables, setTables] = useState<[]>(props.tables);

  useEffect(() => {
    const cancel = new AbortController();
    const int = setInterval(async () => {
      const res = await fetch("https://site.com/wp-json/wp/v2/pages/17", {
        signal: cancel.signal,
      });
      const data = await res.json();
      setTables(data);
    }, 1000);

    return () => {
      cancel.abort();
      clearInterval(int);
    };
  }, []);

  return <div></div>;
}
@Ray try this ts async function getTables() { const res = await fetch("https://site.com/wp-json/wp/v2/pages/17", { cache: "no-store", }); return res.json(); } export default async function Home() { const tableData = await getTables(); return <Client tables={tableData} />; } // client 'use client' function Client(props) { const [tables, setTables] = useState<[]>(props.tables); useEffect(() => { const cancel = new AbortController(); const int = setInterval(async () => { const res = await fetch("https://site.com/wp-json/wp/v2/pages/17", { signal: cancel.signal, }); const data = await res.json(); setTables(data); }, 1000); return () => { cancel.abort(); clearInterval(int); }; }, []); return <div></div>; }
Thank you very much for the code and your time, I will definitely try it and try to figure it out in order to better understand everything, but it seems I managed to do everything with SWR:
"use client";
import useSWR from "swr";

export default function Home() {
const fetcher = (...args) => fetch(...args).then((res) => res.json());

const { data } = useSWR(
"https://site.com/wp-json/wp/v2/pages/17",
fetcher,
{ refreshInterval: 1000 }
);
}

at first glance, everything works as it should, I hope when I transfer this data to the child components, they will also be updated, I will check now
Something like this
const { data } = useSWR(
    "https://site.com/wp-json/wp/v2/pages/17",
    fetcher,
    process.env.NODE_ENV === 'production' ? { refreshInterval: 1000 } : {refreshInterval: 10000},
  );
@Northern Wheatear Something like this const { data } = useSWR( "https://site.com/wp-json/wp/v2/pages/17", fetcher, process.env.NODE_ENV === 'production' ? { refreshInterval: 1000 } : {refreshInterval: 10000}, );
No, I don't think that's necessary, it's an inside story for two people. One fills in the data in the admin area, and the second shows his screen with an open page for other people. The page itself is only accessible to two people
Northern Wheatear
Oh okay
@Northern Wheatear Oh okay
for some reason i have this error when on page connect component <Card> that have "use server" inside to fetch data to get card info

Unhandled Runtime Error
TypeError: Cannot read properties of undefined (reading 'acf')
{JSON.stringify(data.acf.s1r1p1.c1[0].ID)}

Card component code:
"use server";
import Image from "next/image";

async function getCard(id) {
const res = await fetch(
https://site.com/wp-json/wp/v2/card/${id}?_embed,
{
cache: "no-store",
}
);
if (!res.ok) {
throw new Error("Failed to fetch data");
}
return res.json();
}

export default async function Card(cardId) {
const id = cardId.cardId;
const card = await getCard(id);
@Ray only put `'use server'` on a file contain server action
thanks, delete this from component

in general, what is the task:
1) on the page I get a list of the ids of all the necessary records (the list of these records is updated by interval, as already done)
2) passing the id to the card component
3) inside the Card component I make a request to receive the data of the selected desired record (the card data is unchanged, the main thing is to request them by ID)
if i print Card id on page this work
{data.acf.s1r1p1.c1[0].ID}

but when i pass this id to prop then not work and get error
<Card cardId={data.acf.s1r1p1.c1[0].ID} />

Unhandled Runtime Error
TypeError: Cannot read properties of undefined (reading 'acf')
51 | {data.acf.s1r1p1.c1[0].ID}
Northern Wheatear
Can you share the contents of the file where Card is used
@Northern Wheatear Can you share the contents of the file where Card is used
"use client";
import useSWR from "swr";

import Image from "next/image";
import Card from "./components/card";

export default function Home() {
const fetcher = (...args) => fetch(...args).then((res) => res.json());

const { data } = useSWR(
"https://kkkotiqqq.ru/wp-json/wp/v2/pages/17",
fetcher,
{ refreshInterval: 1000 }
);

return (
<main className=" p-10">
{data.acf.s1r1p1.c1[0].ID}

{/* <Card cardId={data.acf.s1r1p1.c1[0].ID} /> */}

</main>
);
}
Oh, this error appears even if you reload the page with a cache reset 😦
TypeError: Cannot read properties of undefined (reading 'acf')
33 | {data.acf.s1r1p1.c1[0].ID}
  const { data } = useSWR(
    "https://kkkotiqqq.ru/wp-json/wp/v2/pages/17",
    fetcher,
    { refreshInterval: 1000 }
  );
  if (!data) return <div>loading...</div>
@Ray ts const { data } = useSWR( "https://kkkotiqqq.ru/wp-json/wp/v2/pages/17", fetcher, { refreshInterval: 1000 } ); if (!data) return <div>loading...</div>
now work thanks
when simple print on page:
{data.acf.s1r1p1.c1[0].ID}

but when paste component, loading is infinite
card component code:
import Image from "next/image";

async function getCard(id) {
  const res = await fetch(
    `https://kkkotiqqq.ru/wp-json/wp/v2/card/${id}?_embed`,
    {
      cache: "no-store",
    }
  );
  if (!res.ok) {
    throw new Error("Failed to fetch data");
  }
  return res.json();
}

export default async function Card(cardId) {
  const id = cardId.cardId;
  const card = await getCard(id);

  return (
    <>
      <div className="card card-winner">
        {/* <Image
          src={card.image_url}
          width={100}
          height={100}
          className="card-image"
        /> */}
        <div>
          <div className="card-title">
            {JSON.stringify(card)}
            {/* {card.title} */}
            {id}
          </div>
          {/* <div className="card-subtitle">{card.acf.subtitle}</div> */}
        </div>
      </div>
    </>

  );
}
Northern Wheatear
You are using Card inside a client component right? So Card cannot be a server component
So you cannot define function Card as async
@Northern Wheatear You are using Card inside a client component right? So Card cannot be a server component
yes right

so do I need to get the data on the client the same way?
Northern Wheatear
Yep
Northern Wheatear
use SWR
Answer
Guys, thank you very much
You've been incredibly helpful. It seems that everything worked as it should, I can't even believe it 🙂