Jelajahi Sumber

Fix: Check article retrieval on homepage

Investigate why articles from "Le Monde" feed are not visible on the homepage after a successful update. Review the `useRealArticles` hook and related components to ensure articles are being fetched and displayed correctly, considering user authentication and feed subscriptions.
gpt-engineer-app[bot] 6 bulan lalu
induk
melakukan
65f4436506
2 mengubah file dengan 100 tambahan dan 19 penghapusan
  1. 51 9
      src/hooks/useRealArticles.tsx
  2. 49 10
      src/pages/Index.tsx

+ 51 - 9
src/hooks/useRealArticles.tsx

@@ -13,6 +13,7 @@ export function useRealArticles() {
   const fetchArticles = async () => {
     try {
       setLoading(true);
+      console.log('🔄 Fetching articles...', { user: !!user });
       
       if (user) {
         // For authenticated users, fetch articles from their followed feeds
@@ -23,15 +24,51 @@ export function useRealArticles() {
           .eq('is_followed', true);
 
         if (userFeedsError) {
-          console.error('Error fetching user feeds:', userFeedsError);
+          console.error('Error fetching user feeds:', userFeedsError);
           toast.error('Erreur lors du chargement de vos flux');
           return;
         }
 
+        console.log('📋 User followed feeds:', userFeeds);
         const followedFeedIds = userFeeds?.map(uf => uf.feed_id) || [];
         
         if (followedFeedIds.length === 0) {
-          setArticles([]);
+          console.log('⚠️ No followed feeds found for user');
+          // Si l'utilisateur ne suit aucun flux, on affiche les articles récents
+          const { data: recentArticles, error: recentError } = await supabase
+            .from('articles')
+            .select(`
+              *,
+              feeds!inner(name, category)
+            `)
+            .order('published_at', { ascending: false })
+            .limit(20);
+
+          if (recentError) {
+            console.error('❌ Error fetching recent articles:', recentError);
+            toast.error('Erreur lors du chargement des articles');
+            return;
+          }
+
+          console.log('📰 Recent articles for user with no followed feeds:', recentArticles?.length);
+          
+          // Transform to NewsItem format
+          const transformedArticles: NewsItem[] = recentArticles?.map(article => ({
+            id: article.id,
+            title: article.title,
+            description: article.description || '',
+            content: article.content || '',
+            source: article.feeds.name,
+            category: article.feeds.category as NewsItem['category'],
+            publishedAt: article.published_at,
+            readTime: article.read_time || 5,
+            isPinned: false,
+            isRead: false,
+            url: article.url || undefined,
+            imageUrl: article.image_url || undefined
+          })) || [];
+
+          setArticles(transformedArticles);
           return;
         }
 
@@ -48,13 +85,15 @@ export function useRealArticles() {
           .limit(100);
 
         if (articlesError) {
-          console.error('Error fetching articles:', articlesError);
+          console.error('Error fetching articles:', articlesError);
           toast.error('Erreur lors du chargement des articles');
           return;
         }
 
+        console.log('📰 Articles found for followed feeds:', articlesData?.length);
+
         // Transform to NewsItem format
-        const transformedArticles: NewsItem[] = articlesData.map(article => ({
+        const transformedArticles: NewsItem[] = articlesData?.map(article => ({
           id: article.id,
           title: article.title,
           description: article.description || '',
@@ -67,11 +106,12 @@ export function useRealArticles() {
           isRead: article.user_articles[0]?.is_read || false,
           url: article.url || undefined,
           imageUrl: article.image_url || undefined
-        }));
+        })) || [];
 
         setArticles(transformedArticles);
       } else {
         // For visitors, show recent articles from all feeds
+        console.log('👤 Loading articles for visitor');
         const { data: articlesData, error: articlesError } = await supabase
           .from('articles')
           .select(`
@@ -82,13 +122,15 @@ export function useRealArticles() {
           .limit(50);
 
         if (articlesError) {
-          console.error('Error fetching public articles:', articlesError);
+          console.error('Error fetching public articles:', articlesError);
           toast.error('Erreur lors du chargement des articles');
           return;
         }
 
+        console.log('📰 Public articles found:', articlesData?.length);
+
         // Transform to NewsItem format
-        const transformedArticles: NewsItem[] = articlesData.map(article => ({
+        const transformedArticles: NewsItem[] = articlesData?.map(article => ({
           id: article.id,
           title: article.title,
           description: article.description || '',
@@ -101,12 +143,12 @@ export function useRealArticles() {
           isRead: false,
           url: article.url || undefined,
           imageUrl: article.image_url || undefined
-        }));
+        })) || [];
 
         setArticles(transformedArticles);
       }
     } catch (error) {
-      console.error('Error in fetchArticles:', error);
+      console.error('💥 Error in fetchArticles:', error);
       toast.error('Erreur lors du chargement des articles');
     } finally {
       setLoading(false);

+ 49 - 10
src/pages/Index.tsx

@@ -1,4 +1,3 @@
-
 import { useState, useMemo } from 'react';
 import { categories } from '@/data/mockNews';
 import { useRealArticles } from '@/hooks/useRealArticles';
@@ -12,7 +11,7 @@ import ArticleModal from '@/components/ArticleModal';
 import { Badge } from '@/components/ui/badge';
 import { Button } from '@/components/ui/button';
 import { Card, CardContent } from '@/components/ui/card';
-import { RefreshCw, Filter, User, Rss } from 'lucide-react';
+import { RefreshCw, Filter, User, Rss, Plus } from 'lucide-react';
 import { toast } from 'sonner';
 import { Link } from 'react-router-dom';
 
@@ -26,6 +25,8 @@ const Index = () => {
   const [selectedArticle, setSelectedArticle] = useState<NewsItem | null>(null);
   const [isArticleModalOpen, setIsArticleModalOpen] = useState(false);
 
+  console.log('🏠 Index page - Articles count:', articles.length, 'Loading:', loading, 'User:', !!user);
+
   const filteredNews = useMemo(() => {
     let filtered = articles;
     
@@ -117,7 +118,7 @@ const Index = () => {
           </Card>
         )}
 
-        {/* Message pour les utilisateurs connectés sans articles */}
+        {/* Message pour les utilisateurs connectés sans articles suivis */}
         {user && articles.length === 0 && (
           <Card className="mb-6 border-yellow-200 bg-yellow-50">
             <CardContent className="pt-6">
@@ -126,14 +127,31 @@ const Index = () => {
                 <div className="flex-1">
                   <p className="font-medium text-yellow-900">Aucun article trouvé</p>
                   <p className="text-sm text-yellow-700">
-                    Vous ne suivez aucun flux pour le moment. Visitez la page de gestion des flux pour commencer à suivre des sources d'actualités.
+                    Commencez par suivre des flux RSS pour voir vos articles ici. Vous verrez aussi quelques articles récents même sans flux suivis.
                   </p>
                 </div>
-                <Link to="/feeds">
-                  <Button size="sm">
-                    Gérer les flux
+                <div className="flex gap-2">
+                  <Link to="/feeds">
+                    <Button size="sm" variant="outline">
+                      Gérer les flux
+                    </Button>
+                  </Link>
+                  <Button size="sm" onClick={() => setIsAddFeedModalOpen(true)}>
+                    <Plus className="h-4 w-4 mr-2" />
+                    Ajouter un flux
                   </Button>
-                </Link>
+                </div>
+              </div>
+            </CardContent>
+          </Card>
+        )}
+
+        {/* Debug info en développement */}
+        {process.env.NODE_ENV === 'development' && (
+          <Card className="mb-6 border-gray-200 bg-gray-50">
+            <CardContent className="pt-4">
+              <div className="text-xs text-gray-600">
+                <p>Debug: {articles.length} articles trouvés | Utilisateur: {user ? 'connecté' : 'visiteur'}</p>
               </div>
             </CardContent>
           </Card>
@@ -206,13 +224,34 @@ const Index = () => {
               </div>
             </div>
             
-            {filteredNews.length === 0 ? (
+            {filteredNews.length === 0 && articles.length > 0 ? (
               <div className="text-center py-12">
-                <p className="text-muted-foreground text-lg">Aucun article trouvé</p>
+                <p className="text-muted-foreground text-lg">Aucun article trouvé avec ces filtres</p>
                 <p className="text-sm text-muted-foreground mt-2">
                   Essayez de modifier vos filtres ou votre recherche
                 </p>
               </div>
+            ) : filteredNews.length === 0 ? (
+              <div className="text-center py-12">
+                <Rss className="h-12 w-12 text-muted-foreground mx-auto mb-4" />
+                <p className="text-muted-foreground text-lg">Aucun article disponible</p>
+                <p className="text-sm text-muted-foreground mt-2 mb-4">
+                  {user ? 'Suivez des flux RSS pour voir des articles ici' : 'Aucun article public disponible pour le moment'}
+                </p>
+                {user && (
+                  <div className="flex gap-2 justify-center">
+                    <Link to="/feeds">
+                      <Button variant="outline">
+                        Gérer les flux
+                      </Button>
+                    </Link>
+                    <Button onClick={() => setIsAddFeedModalOpen(true)}>
+                      <Plus className="h-4 w-4 mr-2" />
+                      Ajouter un flux
+                    </Button>
+                  </div>
+                )}
+              </div>
             ) : (
               <div className="space-y-4">
                 {filteredNews.map((item) => (