NEXT.js Realtime Data on dynamic route with useSWR and firebase

Viewed 346

this is my first question on stackOverflow - so please tell me if I get something groundbreakingly wrong.

Situation: I am on the next.js framework and want to create a dynamic page e.g [sPoolPage], which should show the data of the specific pool that matches the url -> "/p1" should show the details of pool number 1. As a backend I use google realtime database as in the end I want the data to be updated realTime because it will be subject to a lot of change.

Problem: The data somehow isn't properly fetched and I just can't quite figure out where the problem resides because sometimes it works sometimes it doesn't. I can console log poolStatem which displays the intended data structure but it still gives me the error of poolState being not defined, however if I rewrite the code - it works as intended for as long as the dev server is up. The next day I start the dev server again and am hit with the same error - poolState couldn't be read (when I use a pool state element to pass it into the props)

log result of pool state: enter image description here

import PoolDetails from "../../components/PoolDetails";
import { Fragment, useEffect, useState } from "react";
import useSWR from "swr";
import { useRouter } from "next/router";

export default function SinglePoolPage(props) {
  const router = useRouter();
  const { sPoolPage } = router.query;
  const [poolState, setPoolState] = useState();
  const fetcher = (...args) => fetch(...args).then((res) => res.json());
  const { data, error } = useSWR(
    "https://samplefirebasebackendurl.app/pools.json",
    fetcher
  );
  useEffect(() => {
    if (data) {
      const transformedPools = [];
      for (const key in data) {
        if (key == sPoolPage)
          transformedPools.push({
            id: key,
            name: data[key].name,
            timer: data[key].timer,
          });
      }
      setPoolState(transformedPools);
    }
  }, [data]);
  console.log(poolState);
  return (
    <Fragment>
      <PoolDetails
      ></PoolDetails>
    </Fragment>
  );
}

If somebody has a recommendation to do it simpler I am happy to hear it - thank you in advance!

0 Answers
Related