瀏覽代碼

API Integration Partial Setup

Savio Fernando 1 年之前
父節點
當前提交
687ba39901

+ 24 - 18
components/organisms/Cards/HorizontalNewsCard.js

@@ -12,23 +12,29 @@ const HorizontalNewsCard = ({ style, headline, tagline, category, timestamp, ima
     return (
         <TouchableWithoutFeedback onPress={onPress}>
             <View style={[styles.cardContainer, style]}>
-                <View style={styles.textContainer}>
-                    <View>
-                    <Text style={styles.headline}> {headline ?? "Battlegrounds Mobile India iOS release date"}</Text>
-                    <Text style={styles.tagline}>{tagline ?? "government is the people, for the people, by the people but the people are retarded "}</Text>
+                <>
+                    <View style={styles.textContainer}>
+                        <View>
+                            <Text style={styles.headline}> {headline ?? "Battlegrounds Mobile India iOS release date"}</Text>
+                            <Text style={styles.tagline}>{tagline ?? "government is the people, for the people, by the people but the people are retarded "}</Text>
+                        </View>
+
+                    </View>
+                    <View style={styles.imageContainer}>
+                        <View style={styles.imageSub}>
+                            <Image source={image ?? images.horizontalCard} style={{ aspectRatio: 0.9 }} />
+                        </View>
+
                     </View>
+                </>
+                <View>
                     <View style={styles.descriptors}>
                         <Text style={styles.categoryDescriptor}>{category ?? "Sports"}</Text>
                         <Text style={styles.timeDescriptor}>{timestamp ?? "27 mins ago"}</Text>
                     </View>
-                </View>
-                <View style={styles.imageContainer}>
-                    <View style={styles.imageSub}>
-                        <Image source={image ?? images.horizontalCard} style={{aspectRatio: 0.9}} />
-                    </View>
                     <View style={styles.utilButtons}>
                         <BookmarkButton onPress={true} />
-                        <ShareButton onPress={true}/>
+                        <ShareButton onPress={true} />
                     </View>
                 </View>
             </View>
@@ -50,14 +56,14 @@ const styles = StyleSheet.create({
     },
     imageContainer: {
         width: "45%",
-        
+
     },
     textContainer: {
         width: "55%",
         paddingVertical: fonts.getSize(8),
         paddingLeft: fonts.getSize(16),
-        justifyContent:'flex-start',
-        gap:fonts.getSize(12)
+        justifyContent: 'flex-start',
+        gap: fonts.getSize(12)
     },
     headline: {
         fontFamily: fonts.type.medium,
@@ -70,7 +76,7 @@ const styles = StyleSheet.create({
         fontFamily: fonts.type.regular,
         maxHeight: '40%',
         overflow: 'hidden',
-        
+
     },
     descriptors: {
         flexDirection: 'row',
@@ -82,13 +88,13 @@ const styles = StyleSheet.create({
     timeDescriptor: {
         fontFamily: fonts.type.light
     },
-    imageSub:{
-        alignItems:'center',
-        justifyContent:'center',
+    imageSub: {
+        alignItems: 'center',
+        justifyContent: 'center',
         padding: fonts.getSize(14),
         paddingBottom: 0
     },
-    utilButtons:{
+    utilButtons: {
         flexDirection: 'row',
         alignItems: 'center',
         justifyContent: 'space-around'

+ 82 - 20
components/organisms/Sections/CategorySection.js

@@ -3,39 +3,100 @@ import React from 'react'
 import fonts from '../../../theme/fonts'
 import colors from '../../../theme/colors'
 import { ToggleButton } from 'react-native-paper'
-import HorizontalNewsCard from '../Cards/HorizontalNewsCard'
 import SectionHeader from '../Headers/SectionHeader'
+import HorizontalNewsCardVariant from '../Cards/HorizontalNewsCardVariant'
+import {CATEGORY_URL,ARTICLE_URL} from '../../../utils/Constants/urls'
+import { useConstructor } from '../../../utils/Constants/functions'
+
+
+// * API Handling
 
 const CategorySection = () => {
-    const categories = [ "Sector Update","Finance", "Sports", "Regional Update", "Entertainment"]
-    const news = [{},{},{},{},{}]
-    const [categoryValue, setCategoryValue] = React.useState(categories[0].toLowerCase());
+
+    const [news,setNews] = React.useState({})
+    const updateNewsByCategories = (key, value) => {
+        setNews((prevObject) => ({
+          ...prevObject,
+          [key]: value,
+        }));
+      };
+
+    
+    const [categoryValue, setCategoryValue] = React.useState('');
+    const [categories, setCategories] = React.useState([])
+
+    const fetchCategories = () => {
+        
+        fetch(
+            `http://www.newscout.in/api/v1/menus/?domain=newscout`)
+                        .then((res) => res.json())
+                        .then((json) => {
+                            let categoriesHeading = json.body.results.map((item) => item.heading.name)
+                            setCategories(categoriesHeading)
+                            setNews(categoriesHeading.reduce((result, item) => {
+                                result[item] = []
+                                return result
+                            
+                            },{}))
+                            setCategoryValue(categoriesHeading[0])
+                            return categoriesHeading
+                        })
+                        .catch((err) => console.log(err))
+                        .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((json) => {
+            updateNewsByCategories(category,json.body.results)
+            // categories.forEach((category) => {setNews((prev) => ({...prev,[category]:json.body.results}))})
+            return json.body.results
+        })
+        .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"))
+
+        
+    }
 
 
+    useConstructor( () => {
+        fetchCategories()
+        console.log(`construct ${categories}`)
+        for (let category in categories) {
+            fetchNews(category)
+        }
+       
+    })
 
     return (
         <View style={styles.categoriesContainer}>
-            <SectionHeader label={"Categories"}/>
+            <SectionHeader label={"Categories"} />
             <View style={styles.categoriesPillContainer}>
                 <ScrollView horizontal showsHorizontalScrollIndicator={false}>
-                    <ToggleButton.Group onValueChange={value => {setCategoryValue(value)    }}>
+                    <ToggleButton.Group onValueChange={value => { setCategoryValue(value) }}>
                         {
-                            categories.map((category) => 
-                             <ToggleButton 
-                            icon={() => <Text style={[category.toLowerCase() === categoryValue ? styles.selectedPillText: styles.pillText]}>{category}</Text>}
-                            style={[category.toLowerCase() === categoryValue ? styles.selectedContainer : styles.container, {marginHorizontal: fonts.getSize(4)}]}
-                            value={category.toLowerCase()}
-                            
-                        />)
+                            categories.map((category) =>
+                                <ToggleButton
+                                    key={category}
+                                    icon={() => <Text style={[category === categoryValue ? styles.selectedPillText : styles.pillText]}>{category}</Text>}
+                                    style={[category === categoryValue ? styles.selectedContainer : styles.container, { marginHorizontal: fonts.getSize(4) }]}
+                                    value={category}
+
+                                />)
                         }
                     </ToggleButton.Group>
                 </ScrollView>
             </View>
-            <View style={styles.categoriesNewsContainer}>
-                <ScrollView showsVerticalScrollIndicator={false}>
-                    {news.map((item) => <HorizontalNewsCard key={news.indexOf(item)} style={{marginBottom: fonts.getSize(20)}} onPress={true}/>)}
-                </ScrollView>
-            </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} />) } */}
+                </View>
+            </ScrollView>
         </View>
 
     )
@@ -85,9 +146,10 @@ const styles = StyleSheet.create({
         fontSize: fonts.getSize(12),
         color: colors.quaternaryColor
     },
-    categoriesNewsContainer:{
+    categoriesNewsContainer: {
         paddingHorizontal: fonts.getSize(16),
         paddingTop: fonts.getSize(10),
-        
+        gap: 8
+
     }
 })

+ 1 - 1
components/organisms/Sections/RecentNewsSection.js

@@ -55,7 +55,7 @@ const RecentNewsSection = () => {
       <View style={styles.paginationContainer}>
         {entries.map((item) => {
           const index = entries.indexOf(item)
-          return <MaterialComIcon name={"checkbox-blank-circle"} color={currentCardIndex === index ? colors.tertiaryColor: colors.lightGray} size={12} />
+          return <MaterialComIcon key={index} name={"checkbox-blank-circle"} color={currentCardIndex === index ? colors.tertiaryColor: colors.lightGray} size={12} />
         })}
       </View>
     </View>

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

@@ -12,7 +12,7 @@ const RecentPostsSection = () => {
       <SectionHeader label={"Recents Posts"}/>
       <View style={styles.recentPostsContainer}>
         <ScrollView horizontal showsHorizontalScrollIndicator={false}>
-            {posts.map((item) => <VerticalNewsCard id={posts.indexOf(item)}/>)}
+            {posts.map((item) => <VerticalNewsCard key={posts.indexOf(item)} id={posts.indexOf(item)}/>)}
         </ScrollView>
       </View>  
     </View>

+ 1 - 1
screens/SidebarPage.js

@@ -116,7 +116,7 @@ const SidebarPage = ({ navigation }) => {
                   title={item.title}>
                   {item.subTitles.map((subTitle) => (
                     <List.Item
-                      // key={`${item.title}_${subTitle}`}
+                      key={`${item.title}_${subTitle}`}
                       // key={`${item.title}_${item.subTitles.indexOf(subTitle)}`}
                       //key={`Sidebar_${item.title}_${item.subTitles.indexOf(subTitle)}`}
                       style={styles.accordionItemStyle}

+ 12 - 0
utils/Constants/functions.js

@@ -0,0 +1,12 @@
+import { useState } from "react";
+
+/*
+    Executes before Render
+*/
+export const useConstructor = (callBack = () => {}) => {
+    const [hasBeenCalled, setHasBeenCalled] = useState(false);
+    if (hasBeenCalled) return;
+    callBack();
+    setHasBeenCalled(true);
+  }
+

+ 11 - 0
utils/Constants/urls.js

@@ -0,0 +1,11 @@
+export const BASE_URL = "http://www.newscout.in";
+export const DEFAULT_DOMAIN = "newscout";
+export const PAGINATE_BY = 30;
+export const API_URL_v1 = BASE_URL + "/api/v1/"
+export const API_URL_v2 = BASE_URL + "/api/v2/"
+
+
+
+// * V1 API URLS
+export const CATEGORY_URL = API_URL_v1 + "menus/" 
+export const ARTICLE_URL = API_URL_v1 + `article/search/?domain=${DEFAULT_DOMAIN}`