Browse Source

Altered Data Source for creating Filters

Savio Fernando 1 year ago
parent
commit
f0242193eb
1 changed files with 20 additions and 26 deletions
  1. 20 26
      src/screens/Search/SearchListPage.js

+ 20 - 26
src/screens/Search/SearchListPage.js

@@ -2,10 +2,10 @@ import { FlatList, SafeAreaView, ScrollView, StyleSheet, Text, TouchableOpacity,
 import React, { useState } from 'react'
 import React, { useState } from 'react'
 import colors from '../../constants/colors'
 import colors from '../../constants/colors'
 import { horizontalScale, moderateScale, verticalScale } from '../../constants/metrics'
 import { horizontalScale, moderateScale, verticalScale } from '../../constants/metrics'
-import { useConstructor } from '../../utils/functions'
+import { navigateToArticle, useConstructor } from '../../utils/functions'
 import IonIcon from 'react-native-vector-icons/Ionicons'
 import IonIcon from 'react-native-vector-icons/Ionicons'
 import { Checkbox, IconButton, List, Modal, PaperProvider, Portal, ToggleButton } from 'react-native-paper'
 import { Checkbox, IconButton, List, Modal, PaperProvider, Portal, ToggleButton } from 'react-native-paper'
-import { getArticlesBySearch, getMenus } from '../../api/data'
+import { getArticlesBySearch} from '../../api/data'
 import NewscoutCenteredTitleHeader from '../../components/molecules/Header/NewscoutCenteredTitleHeader'
 import NewscoutCenteredTitleHeader from '../../components/molecules/Header/NewscoutCenteredTitleHeader'
 import LoadingScreen from '../../components/organisms/Sections/LoadingScreen'
 import LoadingScreen from '../../components/organisms/Sections/LoadingScreen'
 import ThemedTextButton from '../../components/molecules/Buttons/ThemeTextButton'
 import ThemedTextButton from '../../components/molecules/Buttons/ThemeTextButton'
@@ -22,7 +22,7 @@ const SearchListPage = props => {
 
 
     const [filtersData, setFiltersData] = useState({})
     const [filtersData, setFiltersData] = useState({})
     const [currentFilter, setCurrentFilter] = useState("Category")
     const [currentFilter, setCurrentFilter] = useState("Category")
-    const [pagesLoaded, setPagesLoaded] = useState(1)
+    const [pagesLoaded, setPagesLoaded] = useState(0)
     const [news, setNews] = useState([])
     const [news, setNews] = useState([])
 
 
     const [isFiltersVisible, setFiltersVisible] = useState(false);
     const [isFiltersVisible, setFiltersVisible] = useState(false);
@@ -123,41 +123,38 @@ const SearchListPage = props => {
         setNews([])
         setNews([])
         hideFilters()
         hideFilters()
         setPagesLoaded(1)
         setPagesLoaded(1)
-        console.log(createFilters(filtersData))
         fetchSearchResults(params.query, 1, createFilters(filtersData))
         fetchSearchResults(params.query, 1, createFilters(filtersData))
     }
     }
 
 
-    const clearAllFilters = () => {
-        setFiltersData(prev => ({ ...prev, "Category": Object.entries(filtersData['Category']).reduce((current, value) => ({ ...current, [value[0]]: false }), {}) }))
-        setFiltersData(prev => ({ ...prev, "Source": Object.entries(filtersData['Source']).reduce((current, value) => ({ ...current, [value[0]]: false }), {}) }))
-        setFiltersData(prev => ({ ...prev, "Hash Tags": Object.entries(filtersData['Hash Tags']).reduce((current, value) => ({ ...current, [value[0]]: false }), {}) }))
-    }
+    const _clearFilters = (data) => setFiltersData(Object.entries(data).reduce((current,value) => ({...current,[value[0]]:value[1].reduce((prev,item) => ({...prev,[item.key]: false}),{})}),{}))
 
 
-    const fetchFilters = () => {
-        getMenus()
-            .then(res => {
-                let filtersPayload = res.data.body.results
-                //Reduce Submenus into a object
-                setFiltersData(prev => ({ ...prev, "Category": filtersPayload.flatMap(item => item.heading.submenu.map(category => category.name)).reduce((current, value) => ({ ...current, [value]: false }), {}) }))
-                setFiltersData(prev => ({ ...prev, "Source": filtersPayload.flatMap(item => item.heading.submenu.map(category => category.name)).reduce((current, value) => ({ ...current, [value]: false }), {}) }))
-                setFiltersData(prev => ({ ...prev, "Hash Tags": filtersPayload.flatMap(item => item.heading.submenu.map(category => category.hash_tags.map(tag => tag.name))).reduce((current, value) => ({ ...current, [value]: false }), {}) }))
-
-            })
+    const clearAllFilters = () => {
+        _clearFilters(filtersData)
     }
     }
 
 
     const fetchSearchResults = (search_text, page = 1, filters = "") => {
     const fetchSearchResults = (search_text, page = 1, filters = "") => {
         getArticlesBySearch(search_text, page, filters)
         getArticlesBySearch(search_text, page, filters)
-            .then(res => setNews(prev => [...prev, ...res.data.body.results]))
+            .then(res => {
+                setNews(prev => [...prev, ...res.data.body.results])
+                if (pagesLoaded <= 0){
+                    setCurrentFilter(Object.entries(res.data.body.filters)[0][0])
+                    _clearFilters(res.data.body.filters)
+                    setPagesLoaded(1)
+                    console.log(Object.entries(res.data.body.filters)[2][0])
+                   
+                }
+            })
             .catch(err => console.log(err))
             .catch(err => console.log(err))
     }
     }
 
 
+    const humanizeFilters = (text) => text.split("_").map(item => item[0].toUpperCase() + item.substring(1)).join(" ")
 
 
     const createFilters = (filterObject) => {
     const createFilters = (filterObject) => {
         let filterText = ""
         let filterText = ""
         for (const obj of Object.entries(filterObject)) {
         for (const obj of Object.entries(filterObject)) {
             for (const category of Object.entries(obj[1])) {
             for (const category of Object.entries(obj[1])) {
                 if (category[1] === true) {
                 if (category[1] === true) {
-                    filterText += `&${obj[0].toLowerCase()}=${category[0]}`
+                    filterText += `&${obj[0]}=${category[0]}`
                 }
                 }
             }
             }
         }
         }
@@ -165,7 +162,6 @@ const SearchListPage = props => {
     }
     }
 
 
     useConstructor(() => {
     useConstructor(() => {
-        fetchFilters()
         fetchSearchResults(params.query, 1, createFilters(filtersData))
         fetchSearchResults(params.query, 1, createFilters(filtersData))
     })
     })
 
 
@@ -207,7 +203,7 @@ const SearchListPage = props => {
                                                                 ? styles.selectedPillText
                                                                 ? styles.selectedPillText
                                                                 : styles.pillText,
                                                                 : styles.pillText,
                                                         ]}>
                                                         ]}>
-                                                        {item}
+                                                        {humanizeFilters(item)}
                                                     </Text>
                                                     </Text>
                                                 )}
                                                 )}
                                                 style={[
                                                 style={[
@@ -224,7 +220,6 @@ const SearchListPage = props => {
                         </View>
                         </View>
 
 
                         {
                         {
-                            // filtersData[currentFilter] 
                             Object.keys(filtersData).length <= 0 ? <LoadingScreen />
                             Object.keys(filtersData).length <= 0 ? <LoadingScreen />
                                 :
                                 :
                                 <FlatList
                                 <FlatList
@@ -247,14 +242,13 @@ const SearchListPage = props => {
                                         />}
                                         />}
 
 
                                     />}
                                     />}
-                                // keyExtractor={item => item.index}
                                 />}
                                 />}
                         <ThemedTextButton onPress={applyFilters} theme={'secondary-contained'} title={'Apply'} buttonStyle={{ paddingVertical: verticalScale(8), marginTop: verticalScale(8) }} />
                         <ThemedTextButton onPress={applyFilters} theme={'secondary-contained'} title={'Apply'} buttonStyle={{ paddingVertical: verticalScale(8), marginTop: verticalScale(8) }} />
                     </Modal>
                     </Modal>
                 </Portal>
                 </Portal>
                 <NewscoutCenteredTitleHeader title={"Search Results"} backButtonShown={true} onBackClick={() => navigation.goBack()}>
                 <NewscoutCenteredTitleHeader title={"Search Results"} backButtonShown={true} onBackClick={() => navigation.goBack()}>
                     <TouchableOpacity style={styles.filtersButton} onPress={showFilters}>
                     <TouchableOpacity style={styles.filtersButton} onPress={showFilters}>
-                        <IonIcon name="filter" color={colors().recessive_variant} size={moderateScale(24)} />
+                        <IonIcon name="filter" color={colors().primaryColor} size={moderateScale(24)} />
                     </TouchableOpacity>
                     </TouchableOpacity>
                 </NewscoutCenteredTitleHeader>
                 </NewscoutCenteredTitleHeader>
                 {
                 {