Auto-Refreshing Data
In many applications, especially those displaying real-time or frequently changing data like dashboards, stock tickers,
or live scores, it's essential to keep the information up-to-date without requiring the user to manually refresh the
page. Hyper-fetch provides a simple and efficient way to achieve this with the refresh options in the useFetch hook.
What you'll learn
- How to automatically refresh data at a set interval.
- How to use the
refreshandrefreshTimeoptions inuseFetch. - How to create a live-updating component to display fresh data.
- How to use
Timeenum for clear and readable time definitions.
Polling with refresh
You can turn any useFetch hook into a polling mechanism by setting the refresh option to true and providing a
refreshTime in milliseconds.
import { Time } from "@hyper-fetch/core"
function LiveActivityFeed() {
const [lastUpdated, setLastUpdated] = React.useState(new Date());
const { data: activities, loading } = useFetch(getActivities, {
refresh: true,
refreshTime: Time.second * 5,
onSuccess: () => {
setLastUpdated(new Date());
},
});
return (
<div className="border rounded-md">
<div className="p-4 border-b flex justify-between items-center">
<h2 className="text-xl font-bold">Live Activity</h2>
<p className="text-sm text-gray-500">Last Updated: {lastUpdated.toLocaleTimeString()}</p>
</div>
{loading && !activities ? (
<p className="p-4">Loading feed...</p>
) : (
<ul className="divide-y divide-gray-200">
{activities?.map((activity) => (
<li key={activity.id} className="p-4">
{activity.name}
</li>
))}
</ul>
)}
</div>
);
}
How It Works
refresh: true: This option enables the auto-refreshing feature for the hook.refreshTime: Time.second * 5: This sets the polling interval. We specify that the data should be re-fetched every 5000 milliseconds (5 seconds). Using theTimeenum from@hyper-fetch/coremakes the time definition more readable than just5000.onSuccesscallback: We use theonSuccesscallback to update alastUpdatedstate variable every time a successful refresh occurs. This allows us to give visual feedback to the user that the data is fresh.- The component will now automatically call the
getActivitiesrequest every 5 seconds, keeping the UI in sync with the latest data from the server.
This simple setup is all you need to add powerful real-time capabilities to your application.
Congratulations!
You've learned how to keep your application's data fresh with auto-refreshing!
- You can enable automatic polling for any
useFetchhook. - You know how to configure the refresh interval using
refreshTime. - You can provide visual feedback to users to show when data was last updated.
- You can use the helpful
Timeenum for readable time values.
