{"id":6999,"date":"2023-03-09T03:41:59","date_gmt":"2023-03-09T03:41:59","guid":{"rendered":"https:\/\/www.ardorsys.com\/blog\/?p=6999"},"modified":"2023-03-09T05:00:20","modified_gmt":"2023-03-09T05:00:20","slug":"creating-dynamic-scorecard-with-live-updates-in-next-js","status":"publish","type":"post","link":"https:\/\/www.ardorsys.com\/blog\/creating-dynamic-scorecard-with-live-updates-in-next-js\/","title":{"rendered":"Creating Dynamic Scorecard with Live Updates in Next.js"},"content":{"rendered":"<p>Next.js is a widely used JavaScript framework for building <a href=\"https:\/\/www.ardorsys.com\/blog\/react-18-2-new-features-improvements-and-how-to-use-them\/\">server-rendered React applications<\/a>. It offers a great set of features that allow developers to easily create highly performant and scalable web applications. In this article, we will be exploring how to build a dynamic score card with a loading effect and live updates every 5 seconds in a Next.js application.<\/p>\n<p><strong>Step 1: Create the Score Card Component<\/strong><\/p>\n<p>The first step is to create a <code>ScoreCard<\/code> component that renders the score card. This component should have a state variable <code>loading<\/code> that is set to <code>true<\/code> when the component first mounts and is set to <code>false<\/code> once the data is loaded. We can use the <code>useState<\/code> hook from React to create this state variable.<\/p>\n<pre lang=\"javascript\" escaped=\"true\">\r\nimport { useState, useEffect } from 'react';\r\n\r\nfunction ScoreCard({ score }) {\r\n  const [loading, setLoading] = useState(true);\r\n\r\n  useEffect(() => {\r\n    setLoading(false);\r\n  }, [score]);\r\n\r\n  if (loading) {\r\n    return <div>Loading...<\/div>;\r\n  }\r\n\r\n  return (\r\n    <div>\r\n      <h1>Score: {score}<\/h1>\r\n    <\/div>\r\n  );\r\n}\r\n\r\n<\/pre>\n<p>In this example, we are using the <code>useEffect<\/code> hook to set the <code>loading<\/code> state variable to <code>false<\/code> once the score data is loaded. This will trigger a re-render of the component and display the score.<\/p>\n<p><strong>Step 2: Create the Interval Hook<\/strong><\/p>\n<p>The next step is to create a <code>useInterval<\/code> hook that can be used to update the score every 5 seconds. This hook will use the <code>setInterval<\/code> JavaScript function to call a callback function every 5 seconds.<\/p>\n<pre lang=\"javascript\" escaped=\"true\">\r\nimport { useState, useEffect } from 'react';\r\n\r\nfunction useInterval(callback, delay) {\r\n  const [intervalId, setIntervalId] = useState(null);\r\n\r\n  useEffect(() => {\r\n    function tick() {\r\n      callback();\r\n    }\r\n\r\n    if (delay !== null) {\r\n      const id = setInterval(tick, delay);\r\n      setIntervalId(id);\r\n    }\r\n\r\n    return () => {\r\n      clearInterval(intervalId);\r\n    };\r\n  }, [callback, delay]);\r\n}\r\n\r\n<\/pre>\n<p><strong>Step 3: Use the Score Card and Interval Hook in the Main Page<\/strong><\/p>\n<p>In the main <code>index<\/code> page of our <a href=\"https:\/\/www.ardorsys.com\/blog\/building-web-apps-with-node-js-advantages-limitations-and-best-practices\/\">Next.js application<\/a>, we can use the <code>useInterval<\/code> hook and the <code>ScoreCard<\/code> component to create the score card widget with live updates.<\/p>\n<pre lang=\"javascript\" escaped=\"true\">\r\nimport { useState } from 'react';\r\nimport ScoreCard from '.\/ScoreCard';\r\nimport useInterval from '.\/useInterval';\r\n\r\nexport default function Home() {\r\n  const [score, setScore] = useState(0);\r\n\r\n  useInterval(() => {\r\n    setScore(prevScore => prevScore + 1);\r\n  }, 5000);\r\n\r\n  return (\r\n    <div>\r\n      <ScoreCard score={score} \/>\r\n    <\/div>\r\n  );\r\n}\r\n\r\n<\/pre>\n<p>In this example, we are using the <code>useState<\/code> hook to create a state variable for the score and the <code>useInterval<\/code> hook to update the score every 5 seconds. We pass the <code>setScore<\/code> function as a callback to the <code>useInterval<\/code> hook, which will increment the score by 1 every 5 seconds.<\/p>\n<blockquote><p><strong>Read more:<\/strong>\u00a0<a href=\"https:\/\/www.ardorsys.com\/blog\/lazy-loading-components-on-scroll-in-react-next-js-improve-performance\/\" rel=\"bookmark\">Lazy Loading Components on Scroll in React Next.js: Improve Performance<\/a><\/p><\/blockquote>\n<p><strong>Step 4: Adding a Loading Spinner<\/strong><\/p>\n<p>To make the score card widget more visually appealing, we can add a loading spinner to the <code>ScoreCard<\/code> component while the score is being loaded. We can use a popular library such as &#8220;react-spinners&#8221; to accomplish this.<\/p>\n<pre lang=\"javascript\" escaped=\"true\">\r\nimport { useState, useEffect } from 'react';\r\nimport { CircleLoader } from 'react-spinners';\r\n\r\nfunction ScoreCard({ score }) {\r\n  const [loading, setLoading] = useState(true);\r\n\r\n  useEffect(() => {\r\n    setLoading(false);\r\n  }, [score]);\r\n\r\n  if (loading) {\r\n    return (\r\n      <div className=\"loading-spinner\">\r\n        <CircleLoader size={30} color={'#123abc'} loading={loading} \/>\r\n      <\/div>\r\n    );\r\n  }\r\n\r\n  return (\r\n    <div>\r\n      <h1>Score: {score}<\/h1>\r\n    <\/div>\r\n  );\r\n}\r\n\r\n<\/pre>\n<p>You can then style the <code>loading-spinner<\/code> class in your CSS to center the loading spinner on the page.<\/p>\n<p><strong>Step 5: Error Handling<\/strong><\/p>\n<p>It&#8217;s always a good practice to add some error handling in case the data loading fails. We can add a state variable <code>error<\/code> and call the setError method in case of an error while loading the data.<\/p>\n<pre lang=\"javascript\" escaped=\"true\">\r\nimport { useState, useEffect } from 'react';\r\n\r\nfunction ScoreCard({ score }) {\r\n  const [loading, setLoading] = useState(true);\r\n  const [error, setError] = useState(false);\r\n  \r\n  useEffect(() => {\r\n    setLoading(false);\r\n  }, [score]);\r\n\r\n  if (loading) {\r\n    return <div>Loading...<\/div>;\r\n  }\r\n  if (error) {\r\n    return <div>Error Occured while loading data<\/div>;\r\n  }\r\n\r\n  return (\r\n    <div>\r\n      <h1>Score: {score}<\/h1>\r\n    <\/div>\r\n  );\r\n}\r\n<\/pre>\n<h3><strong>Conclusion:<\/strong><\/h3>\n<p>In this blog post, we have discussed how to create a score card widget with a loading effect and live updates every 5 seconds in a Next.js application. We have used the <code>useState<\/code> and <code>useEffect<\/code> hooks from React to create the score card component and the interval hook. We have also added a loading spinner and error handling to make the score card widget more visually appealing and robust. This is a basic example to give an idea about how you can create a score card widget with loading effect &amp; live update after every 5 sec in Next.js. You can further customize and optimize the code as per your requirements.<\/p>\n","protected":false},"excerpt":{"rendered":"Next.js is a widely used JavaScript framework for building server-rendered React applications. It offers a great set of features that allow developers to easily create highly performant and scalable web applications.\n","protected":false},"author":1,"featured_media":7056,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[150,62],"tags":[179,64,96],"class_list":{"0":"post-6999","1":"post","2":"type-post","3":"status-publish","4":"format-standard","5":"has-post-thumbnail","7":"category-javascript","8":"category-react","9":"tag-next-js","10":"tag-reactjs","11":"tag-reactjs-development"},"aioseo_notices":[],"_links":{"self":[{"href":"https:\/\/www.ardorsys.com\/blog\/wp-json\/wp\/v2\/posts\/6999","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.ardorsys.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.ardorsys.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.ardorsys.com\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.ardorsys.com\/blog\/wp-json\/wp\/v2\/comments?post=6999"}],"version-history":[{"count":5,"href":"https:\/\/www.ardorsys.com\/blog\/wp-json\/wp\/v2\/posts\/6999\/revisions"}],"predecessor-version":[{"id":7059,"href":"https:\/\/www.ardorsys.com\/blog\/wp-json\/wp\/v2\/posts\/6999\/revisions\/7059"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.ardorsys.com\/blog\/wp-json\/wp\/v2\/media\/7056"}],"wp:attachment":[{"href":"https:\/\/www.ardorsys.com\/blog\/wp-json\/wp\/v2\/media?parent=6999"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.ardorsys.com\/blog\/wp-json\/wp\/v2\/categories?post=6999"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.ardorsys.com\/blog\/wp-json\/wp\/v2\/tags?post=6999"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}