简体   繁体   中英

How to input realtime data into NextJS?

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.

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

} 在此处输入图像描述

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

I look forward to working with you on this issue.

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

// This function will return Promise that resolves required data
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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM