最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to input realtime data into NextJS? - Stack Overflow

programmeradmin3浏览0评论

I am just starting to learn Next.js framework.

I need help to solve a problem that I do not understand right now. In normal Vanilla JavaScript and React I can display the resulting API in HTML using the setInterval method.

My API changes data in every 3 seconds. I want to incorporate such variable data into my Next.js app.

Below I have bined the two APIs into a single props to carry data to other ponents.

export async function getServerSideProps(context) {
    const [twoDApiRes, saveApiRes] = await Promise.all([
        fetch(_liveResult),
        fetch(_localTxt),
    ]);

    const [twoDApi, saveApi] = await Promise.all([
        twoDApiRes.json(),
        saveApiRes.text(),
    ]);

    // Regex
    let csv_data = saveApi.split(/\r?\n|\r/);

    // Loop through
    const retrieveData = csv_data.map((el) => {
        let cell_data = el.split(',');

        return cell_data;
    });

    return {
        props: { twoDApi, retrieveData },
    };
}

The main thing to know is that you want to change the data every three seconds in Next.js getServerSideProps.

I am just starting to learn Next.js framework.

I need help to solve a problem that I do not understand right now. In normal Vanilla JavaScript and React I can display the resulting API in HTML using the setInterval method.

My API changes data in every 3 seconds. I want to incorporate such variable data into my Next.js app.

Below I have bined the two APIs into a single props to carry data to other ponents.

export async function getServerSideProps(context) {
    const [twoDApiRes, saveApiRes] = await Promise.all([
        fetch(_liveResult),
        fetch(_localTxt),
    ]);

    const [twoDApi, saveApi] = await Promise.all([
        twoDApiRes.json(),
        saveApiRes.text(),
    ]);

    // Regex
    let csv_data = saveApi.split(/\r?\n|\r/);

    // Loop through
    const retrieveData = csv_data.map((el) => {
        let cell_data = el.split(',');

        return cell_data;
    });

    return {
        props: { twoDApi, retrieveData },
    };
}

The main thing to know is that you want to change the data every three seconds in Next.js getServerSideProps.

Share Improve this question edited Feb 7, 2022 at 8:07 juliomalves 50.6k23 gold badges178 silver badges169 bronze badges asked Mar 20, 2021 at 12:06 Chan LayChan Lay 1441 gold badge3 silver badges15 bronze badges 1
  • create a custom hook – Tilak Madichetti Commented Mar 21, 2021 at 0:32
Add a ment  | 

2 Answers 2

Reset to default 2

You can use useEffect hook to refresh data every 3 seconds.

// This function will return Promise that resolves required data
async function retrieveData() {
  // retrieves data from the server
}

function MyPage() {
  const [data, setData] = useState();
  const [refreshToken, setRefreshToken] = useState(Math.random());
  
  useEffect(() => {
    retriveData()
      .then(setData)
      .finally(() => {
        // Update refreshToken after 3 seconds so this event will re-trigger and update the data
        setTimeout(() => setRefreshToken(Math.random()), 3000);
      });
  }, [refreshToken]);

  return <div>{data?.name}</div>
}

Or you can use react-query library with {refetchInterval: 3000} options to refetch data every 3 seconds.

Here's an example for using react-query.

you can fetch data every 3 seconds in next js 13 or latest App Router

 import React, { useEffect } from 'react';

const Page = () => {
  const [data, setData] = useState(null);

  useEffect(() => {
    const interval = setInterval(() => {
      fetch(`https://api.coincap.io/v2/assets/bitcoin`, { cache: 'no-store' })
        .then(res => res.json())
        .then(data => setData(data));
    }, 3000);

    return () => clearInterval(interval);
  }, []);

  return (
    <>
      <div>
        <p>Symbol: {data?.data?.symbol}</p>
        <p>Name: {data?.data?.name}</p>
        <p>Price: {data?.data?.priceUsd}</p>
        <p>Market Cap: {data?.data?.marketCapUsd}</p>
      </div>
    </>
  );
};

export default Page;
发布评论

评论列表(0)

  1. 暂无评论