How to listen for changes and update state?

I'm would like to listen for changes in the database, and when a specific column has changes with a specific id, then I would like to update the state "role".

Here is my current code:

 const { isLoading, user, error } = useUser();
 const [role, setRole] = useState(null);

  async function fetchRole() {
    const data = await supabaseClient
      .from("roles")
      .select("role")
      .eq("id", user?.id)
      .single();
    setRole(data?.data?.role);
  }

  useEffect(() => {
    fetchRole();
  }, [role]);

How can I listen for changes in the database and then change the state? I have looked at .subscribe() but I'm not sure how to implement it.
Was this page helpful?