简体   繁体   中英

Next.js live price updates from GetServerSideProps props

I'am trying to fetch live price of bitcoin from CoinGecko. I have async GetServerSideProps in index.js that works as intended, and i am passing return props to <Home /> further to <Main /> component, and finally to <Calculatorbuy /> component. Everything works, but i'm getting the price only once on the start. What is the best way to get live price updates? i tried to put props in setInterval inside <CalculatorBuy /> but it just going to pass the same value again and again. My files:

index.js

export default function Home(props) {

  const {data} = props.result;

  return (
    <div className="container">
      <Head>
        <title>Kup BTC</title>
        <meta name="viewport" content="width=device-width, initial-scale=1.0"></meta>
      </Head>
      <Header />

      <Main data={data}/>

      <Footer />
    </div>
  )
}

export async function getServerSideProps(context) {
  const result = await coinGeckoClient.simple.price({
      ids: "bitcoin",
      vs_currencies: "pln",
  });
  return {
      props: {
          result
      },
  }
}
main.js

export default function Main(props) {
    const data = props.data;
    
    return (
        <main className="main">
                <div style={{ display: showMe?"block":"none" }}>
                    <Calculatorbuy data = {data} />
                </div>
        </main>
        )
}

calculatorbuy.js

export default function Calculatorbuy(props) {
    const data = props.data;
    const [value, setValue] = useState(0);
    const currentPrice = parseFloat(data.["bitcoin"].pln);
    console.log(currentPrice);
}

I would like to update the price in calculatorbuy every x seconds

getServerSideProps will make Next.js to generate your page on the server-side on each request using the data returned by getServerSideProps . Your will only fetch the price on the server once per request.

If you need to have live price update, you can use coinGeckoClient in an interval using setInterval in useEffect .

Here is how you would fetch the price on the client-side but you can add an interval function to wrap the following easily.

  const [price, setPrice] = useState();
  useEffect(() => {
    const fetchPrice = async () => {
      const result = await coinGeckoClient.simple.price({
        ids: "bitcoin",
        vs_currencies: "pln",
      });
      setPrice(result);
    };
    fetchPrice();
  })```  

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