0

I'm trying to use the useUser hook from Supabase to fetch the user and then construct a query using the user id but the first time the page loads, I get a runtime error:

Unhandled Runtime Error
TypeError: Cannot read properties of null (reading 'id')

Source
pages/users/[id].js (52:30) @ id

  50 |   .select()
  51 |   .eq("user_id", id)
> 52 |   .eq("follower_id", user.id);

When I refresh, it works fine (I assume because the useUser hook has had time to fetch the user). This is the relevant code snippet.

import { useEffect, useState } from "react";
import supabase from "../../lib/supabase";
import { useUser } from "@supabase/auth-helpers-react";

function User({ props }) {
  const [follows, setFollows] = useState(false);
  const user = useUser();

  const checkFollowStatus = async () => {
    const { data, error } = await supabase
      .from("follows")
      .select()
      .eq("user_id", id)
      .eq("follower_id", user.id);
    if (!error && data) {
      console.log(data);
      setFollows(true);
    } else {
      setFollows(false);
    }
  };

  useEffect(() => {
    checkFollowStatus();
  }, []);
David Stevens
  • 835
  • 1
  • 6
  • 15

1 Answers1

2

You need to check the user exists before calling checkFollowStatus, see this example https://supabase.com/docs/guides/auth/auth-helpers/nextjs#client-side-data-fetching-with-rls

In your case:

  useEffect(() => {
    if (user) checkFollowStatus();
  }, [user]);
Daniel Pérez
  • 1,873
  • 1
  • 17
  • 25