微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

有没有办法使用 getServerSideProps 在 NextJS 中每秒获取数据?

如何解决有没有办法使用 getServerSideProps 在 NextJS 中每秒获取数据?

有没有办法每秒使用 SSR(getServerSideProps) 在 NextJS 中获取 API 数据? 这样客户端会每隔一秒向服务器请求一次获取最新的API数据。

有什么想法吗?

export const getServerSideProps = async () => {
  const res = await fetch(
    "https://api.coingecko.com/api/v3/coins/markets?vs_currency=usd&order=market_cap_desc&per_page=100&page=1&sparkline=false"
  );

  const filteredCoins = await res.json();

  return {
    props: {
      filteredCoins,},};
};

编辑: 这是在我的 index.js 文件中。 我仍然需要从组件返回 filteredCoins

编辑 2:

所以我试过这个:

setInterval(() => {
  async function fetchCoins() {
    const res = await fetch("http://localhost:3000/api/v1/coindata");
    const filteredCoins = await res.json();

    return {
      filteredCoins,};
  }
},1000);

使用此 API 路由:

export default async function coindata(req,res) {
  const apiData = await fetchData();

  res.status(200).json({ data: apiData });
}

async function fetchData() {
  const resp = await fetch(
    "https://api.coingecko.com/api/v3/coins/markets?vs_currency=usd&order=market_cap_desc&per_page=100&page=1&sparkline=false"
  );

  const data = resp.json();

  return data;
}

解决方法

根据您当前的设置方式,您需要每秒重新加载用户浏览器。相反,您应该创建一个 API 路由,并通过 setInterval 从前端查询该 API 路由,API 路由可以具有与您的 getServesideProps 几乎相同的代码,但它不会返回一个对象,而是将与响应一起发回数据。 在 the docs

中了解 next.js API 路由

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。