I'm trying to make a request to Firebase real-time database with useSWR
in my next.js project, but for some reason it always returns null
for both data
and error
variables.
import useSWR from 'swr';
const LastSales: NextPage = () => {
const [sales, setSales] = useState<Sale[]>([]);
const { data, error } = useSWR(
'https://my-app-12345-default-rtdb.firebaseio.com/sales.json'
);
useEffect(() => {
if (!data) return;
const salesArr = [];
for (const key in data) {
salesArr.push({
id: key,
username: data[key].username,
volume: data[key].volume,
});
}
setSales(salesArr);
}, [data]);
if (error) return <p>Failed to load.</p>;
if (sales.length === 0) return <p>Loading...</p>;
return <div>Sales List</div>
Making the same request with fetch
works perfectly fine, but takes up 10x as many lines of code. Why are both data
and error
equal to null
?
CodePudding user response:
According to doc, you need to have a fetcher
to define how it will be called.
const fetcher = (url) => fetch(url).then((res) => res.json());
export default function App() {
const { data, error } = useSWR(
"https://api.github.com/repos/vercel/swr",
fetcher
);