I am following a course where I am fetching data from Firebase using useSWR and using it to set the state. However when I try to console log the data, I get undefined and the screen shows loading. Is there any reason to this. I even copied the exact same code the instructor uses (except the API link).
import { useEffect, useState } from 'react';
import useSWR from 'swr';
function LastSalesPage() {
const [sales, setSales] = useState();
// const [isLoading, setIsLoading] = useState(false);
const { data, error } = useSWR(
'https://nextjs-2021-default-rtdb.firebaseio.com/sales.json'
);
console.log('Data:', data);
useEffect(() => {
if (data) {
const transformedSales = [];
for (const key in data) {
transformedSales.push({
id: key,
username: data[key].username,
volume: data[key].volume,
});
}
setSales(transformedSales);
}
}, [data]);
if (error) {
return <p>Failed to load.</p>;
}
if (!data || !sales) {
return <p>Loading...</p>;
}
return (
<ul>
{sales.map((sale) => (
<li key={sale.id}>
{sale.username} - ${sale.volume}
</li>
))}
</ul>
);
}
export default LastSalesPage;