How to input realtime data into NextJS?

Viewed 3277

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 combined the two APIs into a single props to carry data to other components.

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 },
    };
}

enter image description here

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

1 Answers

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.

Related