Browse Source

Recent News API Integration

Savio Fernando 1 năm trước cách đây
mục cha
commit
003327f880

+ 26 - 22
components/organisms/Sections/CategorySection.js

@@ -1,5 +1,5 @@
 import { StyleSheet, Text, View, ScrollView } from 'react-native'
-import React from 'react'
+import React, { useEffect } from 'react'
 import fonts from '../../../theme/fonts'
 import colors from '../../../theme/colors'
 import { ToggleButton } from 'react-native-paper'
@@ -22,9 +22,9 @@ const CategorySection = () => {
       };
 
     
+
     const [categoryValue, setCategoryValue] = React.useState('');
     const [categories, setCategories] = React.useState([])
-
     const fetchCategories = () => {
         
         fetch(
@@ -33,11 +33,7 @@ const CategorySection = () => {
                         .then((json) => {
                             let categoriesHeading = json.body.results.map((item) => item.heading.name)
                             setCategories(categoriesHeading)
-                            setNews(categoriesHeading.reduce((result, item) => {
-                                result[item] = []
-                                return result
-                            
-                            },{}))
+                            setNews(categoriesHeading.reduce((result, key) => ({ ...result, [key]: []}), {})),
                             setCategoryValue(categoriesHeading[0])
                             return categoriesHeading
                         })
@@ -45,33 +41,41 @@ const CategorySection = () => {
                         .finally(() => console.log("Fetch Categories Executed"))
     }
 
+    
+
     const fetchNews = (category) => {
         fetch(`http://www.newscout.in/api/v1/article/search/?domain=newscout&category=${category}`)
-        .then((response) => response.json())
+        .then(res => res.json())
         .then((json) => {
-            updateNewsByCategories(category,json.body.results)
+            const newsDataFetch = json.body.results
+            const finalNewsData = newsDataFetch.map((article) => ({
+                headline: article.title,
+                image: article.cover_image,
+                category: article.category,
+                root_category: article.root_category,
+                timestamp: article.published_on,
+                tagline: "Bruh Momento Oi Lorem Ipsum di rubi rabbi",
+                id:article.id
+            }),
+            updateNewsByCategories(category,finalNewsData))
             // categories.forEach((category) => {setNews((prev) => ({...prev,[category]:json.body.results}))})
-            return json.body.results
+            return newsDataFetch
         })
         .catch((err) => console.log(err))
-        .finally(() => console.log("Fetch News Executed"))
-        // .then((json) => console.log(`on func ${news[category]}\n${json.results}`))
-        // .catch((err) => console.log(err))
-        // .finally(() => console.log("Fetch News Executed"))
-
-        
+        .finally(() => console.log("Fetch Category News Executed"))
     }
 
 
     useConstructor( () => {
-        fetchCategories()
-        console.log(`construct ${categories}`)
-        for (let category in categories) {
+        const cat_data = fetchCategories()
+        // console.log(`construct ${categories}`)
+        for (let category in cat_data) {
             fetchNews(category)
+
         }
-       
     })
 
+
     return (
         <View style={styles.categoriesContainer}>
             <SectionHeader label={"Categories"} />
@@ -93,8 +97,8 @@ const CategorySection = () => {
             </View>
             <ScrollView showsVerticalScrollIndicator={false}>
                 <View style={styles.categoriesNewsContainer}>
-                    <Text>{console.log(`on html ${news[categoryValue]}`)}</Text>
-                    {/* {news[categoryValue].map((item) => <HorizontalNewsCardVariant key={news.indexOf(item)} style={{ marginBottom: fonts.getSize(20) }} onPress={true} />) } */}
+                    <Text>{console.log(news)}</Text>
+                    {/* {news['Regional Updates'].map((item) => <HorizontalNewsCardVariant />)} */}
                 </View>
             </ScrollView>
         </View>

+ 36 - 10
components/organisms/Sections/RecentNewsSection.js

@@ -8,11 +8,13 @@ import SectionHeader from '../Headers/SectionHeader'
 import metrics from '../../../theme/metrics'
 import Carousel from 'react-native-reanimated-carousel';
 import MaterialComIcon from 'react-native-vector-icons/MaterialCommunityIcons'
+import { useConstructor } from '../../../utils/Constants/functions'
+
 
 
 const ITEM_WIDTH = Math.round(metrics.screenWidth * 0.9);
 const ITEM_HEIGHT = Math.round(ITEM_WIDTH * 3 / 4);
-const entries = [...new Array(6).keys()]
+
 
 const RecentNewsSection = () => {
 
@@ -21,6 +23,32 @@ const RecentNewsSection = () => {
     console.log('current index:', index)
     setCurrentCardIndex(index)
   }
+
+  const [posts,setPosts] = React.useState([{},{},{},{},{}])
+
+  const fetchPosts = () => {
+    fetch("http://www.newscout.in/api/v1/article/search/?domain=newscout&category=Sector%20Updates")
+    .then((res) => res.json())
+    .then((json) => {
+      const postData = json.body.results
+      const finalPostData = postData.map((item)=> ({
+        image:item.cover_image,
+        author: item.author,
+        headline: item.title,
+        id: item.id,
+      }))
+      setPosts(finalPostData)
+      return finalPostData
+    })
+    .catch((err) => console.log(err))
+    .finally(() => console.log("Fetch Posts Executed"))
+  }
+
+  useConstructor(function(){
+    fetchPosts()
+    
+  })
+
   return (
     <View>
       <SectionHeader label={"Recent News"} />
@@ -31,7 +59,7 @@ const RecentNewsSection = () => {
           height={ITEM_HEIGHT}
           style={styles.recentCardContainer}
           autoPlay={true}
-          data={entries}
+          data={posts}
           scrollAnimationDuration={1000}
           mode="parallax"
           modeConfig={{
@@ -39,23 +67,21 @@ const RecentNewsSection = () => {
             parallaxScrollingOffset: 1,
           }}
           onSnapToItem={(index) => updateCurrentIndex(index)}
-          renderItem={({ index }) => (
+          renderItem={({index,item}) => (
             <View style={{ paddingHorizontal: 16 }}>
               <ImageBGCard
-                image={images.imageCard}
-                author={"Ryan Browne"}
-                headline={`Shadow Wizard Money Gang We love casting Spells ${index}`}
+                image={{uri: item.image} ?? images.imageCard}
+                author={ item.author ?? "Anonymous Author"}
+                headline={item.headline ?? `Bruh Moment ${index}`}
               />
             </View>
-
           )}
         />
        
       </View>
       <View style={styles.paginationContainer}>
-        {entries.map((item) => {
-          const index = entries.indexOf(item)
-          return <MaterialComIcon key={index} name={"checkbox-blank-circle"} color={currentCardIndex === index ? colors.tertiaryColor: colors.lightGray} size={12} />
+        {posts.map((item, index) => {
+          return <MaterialComIcon key={`dot_${index}`} name={"checkbox-blank-circle"} color={currentCardIndex === index ? colors.tertiaryColor: colors.lightGray} size={12} />
         })}
       </View>
     </View>

+ 16 - 1
components/organisms/Sections/RecentPostsSection.js

@@ -3,10 +3,25 @@ import React from 'react'
 import SectionHeader from '../Headers/SectionHeader'
 import fonts from '../../../theme/fonts'
 import VerticalNewsCard from '../Cards/VerticalNewsCard'
+import { useConstructor } from '../../../utils/Constants/functions'
 
 const RecentPostsSection = () => {
 
-    const posts = [{},{},{},{},{}]
+  const [posts,setPosts] = React.useState([{},{},{},{},{}])
+
+  const fetchPosts = () => {
+    fetch("http://www.newscout.in/api/v1/article/search/?domain=newscout&category=Sector%20Updates")
+    .then((res) => res.json())
+    .then((json) => setPosts(json.body.results))
+    .then(() => console.log(posts))
+    .catch((err) => console.log(err))
+    .finally(() => console.log("Fetch Posts Executed"))
+  }
+
+  useConstructor(function(){
+    fetchPosts()
+  })
+
   return (
     <View style={styles.container}>
       <SectionHeader label={"Recents Posts"}/>