Basic Spinner Component while Loading Data
Shows how to create a spinner loading component that is displayed while fetching data with useEffect and useState hooks in Next.js 14.
import React, { useState, useEffect } from 'react';
export default function DataLoader() {
// State to track our data
const [data, setData] = useState(null);
// State to track loading
const [loading, setLoading] = useState(true);
useEffect(() => {
// Fetch data from API or perform some async operation
async function fetchData() {
try {
// Simulate async data fetch
const response = await new Promise(resolve => setTimeout(() => resolve('Data loaded'), 2000));
setData(response);
} catch (error) {
console.error('Error fetching data:', error);
} finally {
setLoading(false);
}
}
fetchData();
}, []);
if (loading) {
return <div>Loading...</div>; // Replace with actual spinner component
}
return (
<div>{data}</div>
);
}
This piece of code creates a DataLoader component which fetches data asynchronously and displays a loading indicator (text 'Loading...') while the data is being fetched. Once the data is loaded, it updates the component to display the data. The actual spinner component should replace the loading div.