Bladeren bron

Altered Data Source for creating Filters

Savio Fernando 1 jaar geleden
bovenliggende
commit
f0242193eb
1 gewijzigde bestanden met toevoegingen van 20 en 26 verwijderingen
  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 colors from '../../constants/colors'
 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 { 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 LoadingScreen from '../../components/organisms/Sections/LoadingScreen'
 import ThemedTextButton from '../../components/molecules/Buttons/ThemeTextButton'
@@ -22,7 +22,7 @@ const SearchListPage = props => {
 
     const [filtersData, setFiltersData] = useState({})
     const [currentFilter, setCurrentFilter] = useState("Category")
-    const [pagesLoaded, setPagesLoaded] = useState(1)
+    const [pagesLoaded, setPagesLoaded] = useState(0)
     const [news, setNews] = useState([])
 
     const [isFiltersVisible, setFiltersVisible] = useState(false);
@@ -123,41 +123,38 @@ const SearchListPage = props => {
         setNews([])
         hideFilters()
         setPagesLoaded(1)
-        console.log(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 = "") => {
         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))
     }
 
+    const humanizeFilters = (text) => text.split("_").map(item => item[0].toUpperCase() + item.substring(1)).join(" ")
 
     const createFilters = (filterObject) => {
         let filterText = ""
         for (const obj of Object.entries(filterObject)) {
             for (const category of Object.entries(obj[1])) {
                 if (category[1] === true) {
-                    filterText += `&${obj[0].toLowerCase()}=${category[0]}`
+                    filterText += `&${obj[0]}=${category[0]}`
                 }
             }
         }
@@ -165,7 +162,6 @@ const SearchListPage = props => {
     }
 
     useConstructor(() => {
-        fetchFilters()
         fetchSearchResults(params.query, 1, createFilters(filtersData))
     })
 
@@ -207,7 +203,7 @@ const SearchListPage = props => {
                                                                 ? styles.selectedPillText
                                                                 : styles.pillText,
                                                         ]}>
-                                                        {item}
+                                                        {humanizeFilters(item)}
                                                     </Text>
                                                 )}
                                                 style={[
@@ -224,7 +220,6 @@ const SearchListPage = props => {
                         </View>
 
                         {
-                            // filtersData[currentFilter] 
                             Object.keys(filtersData).length <= 0 ? <LoadingScreen />
                                 :
                                 <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) }} />
                     </Modal>
                 </Portal>
                 <NewscoutCenteredTitleHeader title={"Search Results"} backButtonShown={true} onBackClick={() => navigation.goBack()}>
                     <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>
                 </NewscoutCenteredTitleHeader>
                 {