0

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?

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
chocojunkie
  • 479
  • 2
  • 8
  • 14

1 Answers1

4

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
  );
windmaomao
  • 7,120
  • 2
  • 32
  • 36
  • That worked, thanks. Weird, the online course instructor said it was optional. – chocojunkie Sep 29 '21 at 11:31
  • There might be ways to make it optional, but by default it's not. When in any doubt, check online version, it should be more up-to-date. Could you accept the answer as well, thanks. – windmaomao Sep 29 '21 at 11:33