import React, { useEffect, useRef } from "react"; import { Searchbar, Title, IconButton } from 'react-native-paper'; import { StyleSheet, SafeAreaView, FlatList, View, ActivityIndicator } from 'react-native'; import API from "../API"; import GroupCard from "../components/GroupCard"; import AsyncStorage from '@react-native-async-storage/async-storage'; import i18n from "../i18nMessages.js"; const GROUPS_CACHE_KEY = 'groups_following'; const storeGroupsCache = async (value) => { try { const jsonValue = JSON.stringify(value || []); await AsyncStorage.setItem(GROUPS_CACHE_KEY, jsonValue); } catch (e) { } }; const getGroupsCache = async () => { try { const value = await AsyncStorage.getItem(GROUPS_CACHE_KEY); if (value !== null) return JSON.parse(value); return []; } catch (e) { return []; } }; const Groups = ({navigation}) => { const [searchQuery, setSearchQuery] = React.useState(''); const [searchVisible, setSearchVisible] = React.useState(false); const [groups, setGroups] = React.useState([]); const [loading, setLoading] = React.useState(true); const searchTextBox = useRef(null); const queryTimer = useRef(null); useEffect(() => { let subscribed = true; const getData = async () => { const cached = await getGroupsCache(); if (subscribed) setGroups(Array.isArray(cached) ? cached : []); API.getFollowingGroups('').then((data) => { if (!subscribed) return; const liveGroups = Array.isArray(data?.groups) ? data.groups : []; setGroups(liveGroups); storeGroupsCache(liveGroups); setLoading(false); }).catch(() => { if (subscribed) setLoading(false); }); }; getData(); return () => { subscribed = false; if (queryTimer.current) clearTimeout(queryTimer.current); } }, []) const onChangeSearch = query => { setSearchQuery(query); if (queryTimer.current) clearTimeout(queryTimer.current); setLoading(true); queryTimer.current = setTimeout(() => { if (!query) { return API.getFollowingGroups('').then((data) => { const followingGroups = Array.isArray(data?.groups) ? data.groups : []; setGroups(followingGroups); storeGroupsCache(followingGroups); setLoading(false); }); } API.searchGroups(query).then((data) => { setGroups(Array.isArray(data?.groups) ? data.groups : []); setLoading(false); }) }, 300); }; const renderProfile = (({ item }) => { return (); }); return ( item._id} ListHeaderComponent={ <> {!searchVisible ? { navigation.navigate('NewGroup'); }} /> { setSearchVisible(true); console.log(searchTextBox) //searchTextBox.current.focus(); }} /> : { setSearchVisible(false); }} forwardRef={searchTextBox} /> } {searchQuery ? i18n.t("message.results") : i18n.t("message.yourGroups")} } style={{backgroundColor: "#edf2f7",}} /> {loading && !groups.length ? ( ) : <>} ) } export default Groups; const styles = StyleSheet.create({ container: { padding: 0, }, title: { padding: 10, paddingTop:5, fontSize: 30, marginTop: 15, fontWeight: "bold", color: "#777" }, loader: { position: "absolute", alignSelf: "center", top: 90, } });