react-native#RefreshControl JavaScript Examples

The following examples show how to use react-native#RefreshControl. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: OrderState.js    From haven with MIT License 6 votes vote down vote up
render() {
    const { refreshing, onRefresh, header } = this.props;
    const orders = this.filterOrders();
    return (
      <View style={styles.wrapper}>
        <FlatList
          data={orders}
          keyExtractor={(item, index) => `order_${index}`}
          renderItem={this.renderItem}
          ListHeaderComponent={header}
          ListEmptyComponent={this.renderEmptyContent()}
          refreshControl={
            <RefreshControl
              refreshing={refreshing}
              onRefresh={onRefresh}
            />
          }
        />
      </View>
    );
  }
Example #2
Source File: MultiSigWalletComponent.js    From RRWallet with MIT License 6 votes vote down vote up
render() {
    if (!this.account.hasCreated) {
      return this.renderDefaultPage();
    }
    return (
      <View style={styles.main}>
        <SectionList
          refreshControl={
            <RefreshControl
              refreshing={this.isRefreshing}
              onRefresh={this._onRefresh}
              tintColor={theme.iconColor}
              title={i18n.t("common-loading")}
              titleColor={theme.iconColor}
              colors={["#f00", "#0f0", "#00f"]}
              progressBackgroundColor="#ffffff"
            />
          }
          style={styles.list}
          sections={this.sections}
          ListHeaderComponent={this._renderHeader}
          ListFooterComponent={this._renderFooter}
          ItemSeparatorComponent={this._renderSeparator}
          renderSectionHeader={this._renderSectionHeader}
          stickySectionHeadersEnabled={false}
          onMomentumScrollEnd={this._onMomentumScrollEnd}
          showsVerticalScrollIndicator={false}
          {...this._panResponder.panHandlers}
        />
      </View>
    );
  }
Example #3
Source File: wallet.js    From haven with MIT License 6 votes vote down vote up
render() {
    return (
      <View style={screenWrapper.wrapper}>
        <TabHeader
          title="Wallet"
          left={<NavBackButton white />}
          onLeft={this.handleGoBack}
          right={<NavOptionButton white />}
          onRight={this.handleMoreOption}
        />
        <ScrollView
          style={styles.contentWrapper}
          contentContainerStyle={styles.contentContainer}
          refreshControl={<RefreshControl
            refreshing={this.state.refreshing}
            onRefresh={this.onRefresh}
          />}
        >
          <WalletTemplate />
          <BuyWyre />
          <View style={{ flex: 1 }} />

        </ScrollView>
        <SendReceiveMoney sendMoney={this.handleSend} receiveMoney={this.handleReceive} />
        <OBActionSheet
          ref={this.setActionSheet}
          onPress={this.handleActionSheet}
          options={['View transaction history', 'Cancel']}
          cancelButtonIndex={1}
        />
      </View>
    );
  }
Example #4
Source File: PullToRefresh.js    From actual with MIT License 6 votes vote down vote up
export default function PullToRefresh({ children, onRefresh }) {
  let [refreshing, setRefreshing] = useState(false);

  async function onRefresh_() {
    setRefreshing(true);
    await onRefresh();
    setRefreshing(false);
  }

  return children({
    refreshControl: (
      <RefreshControl refreshing={refreshing} onRefresh={onRefresh_} />
    )
  });
}
Example #5
Source File: index.js    From tcap-mobile with GNU General Public License v3.0 6 votes vote down vote up
render() {
      const {refreshing} = this.state;
      return (
          <SafeAreaView style={styles.wrapper}>
              <StatusBarColor
                  backgroundColor={Colors.primary_bg}
                  barStyle="light-content"
              />
              <ScrollView 
                  refreshControl={
                      <RefreshControl
                          onRefresh={this.onRefresh} refreshing={refreshing} tintColor={Colors.white}
                          title="Refreshing Dashboard"
                          titleColor={Colors.white} />
                  } 
                  showsVerticalScrollIndicator={false}
              >
                  {this.renderContent()}
              </ScrollView>
          </SafeAreaView>
      );
  }
Example #6
Source File: notificationList.js    From Baku with GNU General Public License v3.0 6 votes vote down vote up
render() {
    return <ScrollView refreshControl={
      <RefreshControl refreshing={this.state.refreshing} onRefresh={this._onRefresh} />} contentContainerStyle={{
      flexDirection: 'row',
      justifyContent: 'space-around',
      flexWrap: 'wrap'
    }}>
      {this.listNotifs()}
    </ScrollView>;
  }
Example #7
Source File: ApprovalPage.js    From id.co.moonlay-eworkplace-mobile with MIT License 6 votes vote down vote up
render() {
        return (
            <SafeAreaView style={styles.container}>           
              <FlatList
                keyExtractor={(item, index) => index.toString()}
                data={this.state.people}
                renderItem={({ item }) =>
                    <PeopleCard person={item} date={this.state.monthYear} loadData={this.loadData}/>         
                }
                refreshControl={
                <RefreshControl refreshing={this.state.refreshing} 
                onRefresh={this.loadData}/>}
                style={{display: this.state.people.length !== 0 ? 'flex':'none'}}
              />
              <View style={[styles.view,{display: this.state.people.length === 0 ? 'flex':'none'}]}>
                <FontAwesome5 name='exclamation-triangle' size={80} color='#1A446D' style={{opacity:0.7}}/>
                <Text style={styles.text}>No Approval Request</Text>
              </View>
              <Loading visible={this.state.loadings === true ? true : false}/>
            </SafeAreaView>
        )
    }
Example #8
Source File: index.js    From actual with MIT License 5 votes vote down vote up
render() {
    const {
      currentMonth,
      bounds,
      editMode,
      initialized,
      showBudgetDetails
    } = this.state;
    const {
      categories,
      categoryGroups,
      prefs,
      budgetType,
      navigation,
      applyBudgetAction
    } = this.props;
    let numberFormat = prefs.numberFormat || 'comma-dot';

    if (!categoryGroups || !initialized) {
      return (
        <View
          style={{
            flex: 1,
            backgroundColor: 'white',
            alignItems: 'center',
            justifyContent: 'center'
          }}
        >
          <AnimatedLoading width={25} height={25} />
        </View>
      );
    }

    return (
      <SafeAreaView
        edges={['top']}
        style={{ flex: 1, backgroundColor: colors.p5 }}
      >
        <FocusAwareStatusBar barStyle="light-content" />
        <SyncRefresh onSync={this.sync}>
          {({ refreshing, onRefresh }) => (
            <BudgetTable
              // This key forces the whole table rerender when the number
              // format changes
              key={numberFormat}
              categories={categories}
              categoryGroups={categoryGroups}
              type={budgetType}
              month={currentMonth}
              monthBounds={bounds}
              editMode={editMode}
              navigation={navigation}
              refreshControl={
                <RefreshControl refreshing={refreshing} onRefresh={onRefresh} />
              }
              onEditMode={flag => this.setState({ editMode: flag })}
              onShowBudgetDetails={this.onShowBudgetDetails}
              onPrevMonth={this.onPrevMonth}
              onNextMonth={this.onNextMonth}
              onAddCategory={this.onAddCategory}
              onReorderCategory={this.onReorderCategory}
              onReorderGroup={this.onReorderGroup}
              onOpenActionSheet={this.onOpenActionSheet}
              onBudgetAction={applyBudgetAction}
            />
          )}
        </SyncRefresh>

        {showBudgetDetails && (
          <BudgetSummary
            month={currentMonth}
            onClose={() => this.setState({ showBudgetDetails: false })}
          />
        )}
      </SafeAreaView>
    );
  }
Example #9
Source File: ClockInHistory.js    From id.co.moonlay-eworkplace-mobile with MIT License 5 votes vote down vote up
render() {
        return (
            <SafeAreaView style={{flex:1}}>
                <ScrollView
                alwaysBounceVertical={true} 
                refreshControl={
                  <RefreshControl refreshing={this.state.refreshing} onRefresh={this.loadData} />
                }>
                  <View style={{display: this.state.history.length !== 0 ? 'flex':'none'}}>
                    <Text style={styles.TextTittle}>{this.state.monthYear}</Text>
                    <Card containerStyle={{marginBottom:10}}>
                        {
                            this.state.history.map((u, i) => {
                              const clockinTime = moment(u.CheckIn).add(7, 'hours').format('YYYY-MM-DD hh:mm:ss A');
                              const clockoutTime = moment(u.CheckOut).add(7, 'hours').format('YYYY-MM-DD hh:mm:ss A');
                              const clockin = clockinTime.substr(11,5)+' '+clockinTime.substr(20,15)
                              var clockout = '';
                              if(clockoutTime.substr(11,5) === '07:00' && clockoutTime.substr(20,15) === 'AM'){
                                  clockout = 'Now'
                              }
                              else{
                                  clockout = clockoutTime.substr(11,5)+' '+clockoutTime.substr(20,15)
                              }
                              return (
                              <View key={i} style={styles.history}>
                                  <View style={{flex:1, marginLeft:10, justifyContent:'center'}}>
                                      <Text style={styles.Text}>{u.CheckIn.substr(8,2)+' / '+u.CheckIn.substr(5,2) +' / '+u.CheckIn.substr(0,4)}</Text>
                                  </View>
                                  <View style={{flex:1, alignItems:'flex-end', marginRight:10, justifyContent:'center'}}>
                                      <Text style={styles.Text}>{clockin+'-'+clockout}</Text>
                                  </View>
                              </View>
                              );
                            })
                        }
                    </Card>
                  </View>
                  <View style={{display: this.state.history.length === 0 ? 'flex':'none', alignItems:'center', marginTop:250}}>
                    <FontAwesome5 name='exclamation-triangle' size={80} color='#1A446D' style={{opacity:0.7}}/>    
                    <Text style={[styles.TextStatus]}>No History</Text>
                  </View>
                </ScrollView>
            </SafeAreaView>
        )
    }
Example #10
Source File: index.js    From aws-appsync-refarch-offline with MIT No Attribution 5 votes vote down vote up
function Catalog(props) {

    const [loading, setLoading] = useState(false);
    const [products, setProducts] = useState([]);
    const order = useSelector(state => state.order);
    const dispatch = useDispatch();

    useEffect(() => {
        fetchProducts();
    }, []);

    async function fetchProducts() {
        const data = await DataStore.query(Product);
        setProducts(data);
    };

    function checkoutBtnHandler() {
        return props.navigation.push('Checkout');
    }

    function addProductHandler(product) {
        dispatch(addLineItem(product));
    }
    
    const productList = products.map(product => (
        <ListItem thumbnail key={product.id}>
            <Left>
                <Thumbnail square source={{ uri: product.image }} />
            </Left>
            <Body>
                <Text>{product.name}</Text>
                <Text note numberOfLines={1}>${product.price}</Text>
            </Body>
            <Right>
                <Button onPress={() => addProductHandler(product)}>
                    <Text>Add</Text>
                </Button>
            </Right>
        </ListItem>
    ));

    return (
        <Container>
            <Content refreshControl={
                <RefreshControl
                    onRefresh={fetchProducts}
                    refreshing={loading}
                />
            }>
                <Button block info style={styles.checkoutBtn} onPress={checkoutBtnHandler}>
                    <Text style={styles.quantityText}>{order.totalQty}</Text>
                    <Text style={styles.subtotalTxt}>Subtotal ${order.subtotal.toFixed(2)}</Text>
                </Button>
                <List>
                    {productList}
                </List>
            </Content>
        </Container>
    );
}
Example #11
Source File: index.rn.jsx    From taro-form with MIT License 5 votes vote down vote up
render() {
    const {
      style = {},
      refresh = false,
      emptyIcon = 'info',
      emptyTitle = '什么都没有',
      emptyDesc,
      emptyBttton,
      emptyShow = false,
      scrollWithAnimation = true,
      scrollTop,
      flip = false,
      showsVerticalScrollIndicator = true,
      contentContainerStyle = {},
      flatListParams
    } = this.props
    const { reloadShow } = this.state
    return (
      <View style={{ flex: 1, transform: flip ? [{ rotate: '180deg' }] : [] }} >
        {reloadShow && <View
          className={'app-touch scroll-info' + (emptyShow ? ' scroll-info--show' : '')}
          onClick={this.reload.bind(this)}
          style={(!!emptyBttton ? { zIndex: 1 } : {})}
        >
          <Icon name={emptyIcon} size={90} color='#333' />
          {!!emptyTitle && <Text className='scroll-info__title'>{emptyTitle}</Text>}
          {!!emptyDesc && <Text className='scroll-info__desc'>{emptyDesc}</Text>}
          {!!emptyBttton && <Btn size='m' text={emptyBttton} style={{ marginTop: Taro.pxTransform(20) }} onClick={() => this.props.onEmptyButtonCilck && this.props.onEmptyButtonCilck()} />}
        </View>}
        <ScrollView
          scrollY
          showsVerticalScrollIndicator={showsVerticalScrollIndicator}
          contentContainerStyle={contentContainerStyle}
          {...{
            refreshControl: this.props.onRefresh && <RefreshControl
              refreshing={refresh}
              onRefresh={this.props.onRefresh}
              colors={['rgb(217, 51, 58)']}
            />
          }}
          {...flatListParams}
          style={[{ height: 1 }, style]}
          onScroll={this.scroll.bind(this)}
          onScrollToLower={this.scrollToLower.bind(this)}
          scrollWithAnimation={scrollWithAnimation}
          scrollTop={scrollTop}
          scrollIndicatorInsets={{ right: 1 }}
        >
          {!emptyShow && this.props.children}
        </ScrollView>
      </View>

    )
  }
Example #12
Source File: Theme.js    From RRWallet with MIT License 5 votes vote down vote up
RefreshControl.defaultProps.titleColor = "#FFFFFF";
Example #13
Source File: sick.js    From id.co.moonlay-eworkplace-mobile with MIT License 5 votes vote down vote up
render() {
        return (
            <SafeAreaView style={styles.container2}>
              <ScrollView
                alwaysBounceVertical={true} 
                refreshControl={
                <RefreshControl refreshing={this.state.refreshing} 
                onRefresh={this.findCoordinates} />
              }>
              <View style={{flex:8}}>
                <Text style={styles.textareaContainer}>
                    Please fill this forms
                </Text>
                <Text style={styles.textSM}>
                    Select Your Head Division *
                </Text>

                <View style={styles.viewPicker}>            
                  <Picker
                    mode={"dropdown"}
                    selectedValue={this.state.headDivision}
                    style={styles.picker}
                    onValueChange={(itemValue, itemIndex) =>
                      this.setState({
                        headDivision: itemValue
                      })
                    }>
                    <Picker.Item label='' value=''/>
                    {this.state.listHD.map((u,i) => {
                      return (<Picker.Item key={i} label={u.profile.firstname+' '+u.profile.lastname} value={u.username}/>);
                      })
                    }
                  </Picker>
                </View>

                <Text
                  style={styles.textSM}>
                    Project Name *
                </Text>
                <TextInput
                  style={styles.inputText}
                  maxLength={40}
                  onChangeText={text => this.setState({projectName: text})}
                  value={this.state.projectName}>
                </TextInput>

                <Text
                  style={styles.textSM}>
                    Notes *
                </Text>
                <TextInput
                    multiline={true}
                    placeholder="tell us about your health issue"
                    maxLength={200} 
                    style={styles.textInput}
                    onChangeText={text => this.setState({message: text})}
                    value={this.state.message}>
                </TextInput>
                </View>

                <View style={{flex:1, marginTop:30}}>
                  <TouchableOpacity onPress={this.submitAll} style={styles.buttonSubmit}>
                      <Text style={styles.textbtnSubmit} >Submit</Text>
                  </TouchableOpacity>
                </View>
                
            </ScrollView>
          </SafeAreaView>
        )
    }
Example #14
Source File: Theme.js    From RRWallet with MIT License 5 votes vote down vote up
RefreshControl.defaultProps.title = i18n.t("common-loading");
Example #15
Source File: index.js    From real-frontend with GNU General Public License v3.0 5 votes vote down vote up
SearchComponent = ({
  theme,
  authUser,
  usersSearchRequest,
  usersSearch,
  usersFollow,
  usersFollowRequest,
  usersUnfollow,
  usersUnfollowRequest,
  handleProfilePress,
  usersGetTrendingUsers,
  postsGetTrendingPosts,
  handleFormFocus,
  formFocus,
  handleFormChange,
  formChange,
  themeFetch,
}) => {
  const styling = styles(theme)
  const { t } = useTranslation()

  return (
    <View style={styling.root}>
      <HeaderComponent>
        <FormComponent
          usersSearch={usersSearch}
          usersSearchRequest={usersSearchRequest}
          handleFormFocus={handleFormFocus}
          handleFormChange={handleFormChange}
        />
      </HeaderComponent>

      {!formFocus && (path(['status'])(postsGetTrendingPosts) === 'loading' && !path(['data', 'length'])(postsGetTrendingPosts)) ?
        <PostsLoadingComponent />
      : null}

      {!formFocus ?
        <ScrollView>
          <PostsGridComponent
            postsGet={postsGetTrendingPosts}
            themeFetch={themeFetch}
            themeCode={path(['themeCode'])(authUser)}
          />
        </ScrollView>
      : null}

      {formFocus && formChange ?
        <ScrollView refreshControl={<RefreshControl tintColor={theme.colors.border} refreshing={usersSearch.status === 'loading'} />}>
          <Subheading style={styling.subheading}>{t('Search Result')}</Subheading>
          <ResultComponent
            usersSearch={usersSearch}
            usersFollow={usersFollow}
            usersFollowRequest={usersFollowRequest}
            usersUnfollow={usersUnfollow}
            usersUnfollowRequest={usersUnfollowRequest}
            handleProfilePress={handleProfilePress}
          />
        </ScrollView>
      : null}

      {formFocus && !formChange ?
        <ScrollView refreshControl={<RefreshControl tintColor={theme.colors.border} refreshing={usersGetTrendingUsers.status === 'loading'} />}>
          <Subheading style={styling.subheading}>{t('Trending Users')}</Subheading>
          <ResultComponent
            usersSearch={usersGetTrendingUsers}
            usersFollow={usersFollow}
            usersFollowRequest={usersFollowRequest}
            usersUnfollow={usersUnfollow}
            usersUnfollowRequest={usersUnfollowRequest}
            handleProfilePress={handleProfilePress}
          />
        </ScrollView>
      : null}
    </View>
  )
}
Example #16
Source File: Theme.js    From RRWallet with MIT License 5 votes vote down vote up
RefreshControl.defaultProps.progressBackgroundColor = "#FFFFFF";
Example #17
Source File: Home.js    From Alfredo-Mobile with MIT License 5 votes vote down vote up
Home = props => {
  const { products, navigation } = props
  const [refreshing, setRefreshing] = useState(false)

  useEffect(() => {
    props.getProductsList({ params: '?page=1' })
  }, [])

  const pullRefresh = () => {
    props.getProductsList({ params: '?page=1' })
  }

  const renderItem = ({ item, index }) => (
    <CardProduct
      item={item}
      onPress={() => onPress(item)}
    />
  )

  const onEndReached = async() => {
    const { page, lastPage, isLoadMore } = props.products

    if (!isLoadMore && (page < lastPage)) {
      const newPage = page + 1

      props.moreProducts({ params: `?page=${newPage}`, page: newPage })
    }
  }

  const onPress = (item) => {
    props.getDetail('/' + item?.slug)
    navigation.navigate('ProductDetail', {title: item.title, stock: item.stock})
  }

  return (
    <SafeAreaView style={apply('flex bg-gray-100')}>
      <StatusBar backgroundColor={apply("blue-500")} barStyle='light-content' />
      {products?.fetching ? (
        <View style={styles.emptyState}>
          <ActivityIndicator size="large" color={apply('gray-900')} />
        </View>
      ) : (
        <FlatList
          data={products.data}
          keyExtractor={(item, index) => index.toString()}
          showsVerticalScrollIndicator={false}
          initialNumToRender={8}
          contentContainerStyle={apply('bg-gray-100 py-2')}
          renderItem={renderItem}
          refreshControl={
            <RefreshControl refreshing={refreshing} onRefresh={() => pullRefresh()} />
          }
          onEndReached={onEndReached}
          horizontal={false}
          numColumns={2}
          key={2}
          onEndReachedThreshold={0.1}
          ListEmptyComponent={() =>
            <View style={styles.emptyState}>
              <Text>No data.</Text>
            </View>
          }
          ListFooterComponent={() =>
            products?.isLoadMore && (
              <View style={styles.emptyState}>
                <ActivityIndicator size="large" color={apply("gray-900")} />
              </View>
            )
          }
        />
      )}
    </SafeAreaView>
  )
}
Example #18
Source File: StoreTabs.js    From haven with MIT License 5 votes vote down vote up
render() {
    const {
      profile, peerID, externalStore, onMore,
    } = this.props;
    const { currentTab } = this.state;

    const cover = _.get(profile.data, 'headerHashes.medium');
    const navBarHeight = navHeightStyle.height + statusbarHeight;

    return (
      <ParallaxScrollView
        windowHeight={SCREEN_WIDTH / 3 + navBarHeight}
        backgroundSource={externalStore ? getHeaderImageSource(cover) : getLocalHeaderImageSource(cover)}
        leftIcon={NavBackButton}
        rightIcon={props => <StoreMoreMenu onMore={onMore} {...props} />}
        leftIconOnPress={this.handleBack}
        rightIconOnPress={onMore}
        navBarColor="white"
        navBarTitleColor="black"
        navBarTitle={decode(_.get(profile.data, 'name'))}
        refreshControl={<RefreshControl refreshing={profile.loading} onRefresh={this.handleRefresh} />}
        stickyHeaderIndices={[1]}
        {...this.scrollCallBacks}
        contentContainerStyle={{ paddingTop: SCREEN_WIDTH / 3 - 32 + (Platform.OS === 'android' && statusbarHeight) }}
      >
        <ShopInfo
          peerID={peerID}
          profile={profile.data}
          externalStore={externalStore}
        />
        <Tabs
          currentTab={currentTab}
          tabs={tabs}
          onChange={this.handleTabChange}
        />
        {!peerID && this.renderStickyPart()}
        {this.renderTabContent()}
      </ParallaxScrollView>
    );
  }
Example #19
Source File: index.js    From tcap-mobile with GNU General Public License v3.0 5 votes vote down vote up
TransactionHistory = () =>{
    const isFocused = useIsFocused();
    const walletService = WalletService.getInstance();
    const accAddress =  walletUtils.createAddressFromPrivateKey(walletService.pk);

    const [isLoading, setIsLoading] = useState(false);
    const [list , setList] = useState([]);

    const [refreshing,setRefreshing] = useState(false);

    useEffect(()=>{
        if(isFocused)
            loadHistory();
    },[isFocused]);

    const onRefresh = () =>{
        setRefreshing(true);
        loadHistory();
        setTimeout(()=>{setRefreshing(false);},500);
    };

    const loadHistory = () =>{
        setIsLoading(true);
        apiServices.getTransactionHistory(accAddress)
            .then((data)=>{
                setList(data);
                setIsLoading(false);
            })
            .catch(()=>{
                setIsLoading(false);
            });
    };

    const renderEachItem = ({ index,item }) =>{
        return <HistoryCard historyData={item}  key={index} />;
    };

    return(
        <View style={styles.container}>
            <Text style={styles.titleBar_title}>Transaction Activities</Text>
            <FlatList
                data={list} 
                initialNumToRender={5}
                keyExtractor={item=>item.txnId.toString()}
                refreshControl={
                    <RefreshControl
                        onRefresh={onRefresh} refreshing={refreshing}
                        title="Refreshing History .."
                        titleColor={'#fff'} />
                }
                removeClippedSubviews={true} 
                renderItem = {renderEachItem}
                showsVerticalScrollIndicator={false}
                style={{flex:1,marginTop:moderateScale(20)}}
            />
            <LoadingIndicator
                message={'Please wait while fetching your transactions...'}
                visible={isLoading}
            />
        </View>
    );
}
Example #20
Source File: CategoryScreen.js    From Alfredo-Mobile with MIT License 5 votes vote down vote up
CategoryScreen = (props) => {
  const [refreshing, setRefreshing] = useState(false)
  const { products, navigation } = props

  const slug = navigation.getParam('slug', '')

  useEffect(() => {
    props.showCategory(slug)
  }, [])

  const pullRefresh = () => {
    props.showCategory(slug)
  }

  const renderItem = ({ item, index }) => (
    <CardProduct
      item={item}
      onPress={() => onPress(item)}
    />
  )

  const onPress = (item) => {
    props.getDetail('/' + item?.slug)
    navigation.navigate('ProductDetail', {title: item.title, stock: item.stock})
  }

  return (
    <SafeAreaView style={apply('flex bg-gray-100')}>
      <StatusBar backgroundColor={apply("blue-500")} barStyle='light-content' />
      {products?.fetching ? (
        <View style={styles.emptyState}>
          <ActivityIndicator size="large" color={apply('gray-900')} />
        </View>
      ) : (
        <FlatList
          data={products?.data[0]?.product}
          keyExtractor={(item, index) => index.toString()}
          showsVerticalScrollIndicator={false}
          initialNumToRender={6}
          contentContainerStyle={apply('bg-gray-100 py-2')}
          renderItem={renderItem}
          refreshControl={
            <RefreshControl refreshing={refreshing} onRefresh={() => pullRefresh()} />
          }
          horizontal={false}
          numColumns={2}
          key={2}
          onEndReachedThreshold={0.1}
          ListEmptyComponent={() =>
            <View style={styles.emptyState}>
              <Text>No data.</Text>
            </View>
          }
        />
      )}
    </SafeAreaView>
  )
}
Example #21
Source File: TicketsListing.js    From expo-ticket-app with MIT License 4 votes vote down vote up
TicketsListing = ({ member, loading, reFetch }) => (
    <Container>
        <ImageBackground
            source={require('../../../images/Tickets/no-tickets.png')}
            imageStyle={{
                resizeMode: 'stretch',
                height: 650,
            }}
            style={{
                width: '100%',
                flex: 1,
                backgroundColor: commonColor.backgroundColor,
            }}>
            <StatusBar style="light"/>
            <TextI18n style={{ fontSize: 30, margin: 50, marginBottom: 10, marginLeft: 10 }}>
                tickets.title
            </TextI18n>
            <Content padder refreshControl={(
                <RefreshControl
                    refreshing={loading}
                    onRefresh={reFetch}
                    title="Pull to refresh"
                    tintColor="#fff"
                    titleColor="#fff"
                    colors={["#000", "#fff", "#000"]}
                />
            )}>
                {(member && member.tickets && member.tickets.length)
                    ? (<View>
                        <Spacer size={30}/>
                        <FlatList
                            data={member.tickets}
                            renderItem={({ item, index }) =>
                                (<TouchableOpacity disabled={item.scanned === true}
                                                   onPress={() => Actions.ticketView({ ticket: item })}
                                                   style={{ flex: 1, paddingBottom: 12 }}>
                                    <View style={{
                                        flex: 1,
                                        flexDirection: 'row',
                                        alignItems: 'center',
                                        justifyContent: 'center',
                                        backgroundColor: commonColor.backgroundColor,
                                        borderRadius: 10,
                                        shadowColor: '#000',
                                        shadowOffset: {
                                            width: 0,
                                            height: 3,
                                        },
                                        shadowOpacity: 0.29,
                                        shadowRadius: 4.65,
                                        elevation: 7,
                                        marginLeft: 10,
                                        marginRight: 10,
                                        opacity: item.scanned === true ? 0.6 : 1,
                                        zIndex: 1,
                                    }}>
                                        {item.scanned === true && <View style={{
                                            flex: 1,
                                            flexDirection: 'row',
                                            alignItems: 'center',
                                            justifyContent: 'center',
                                            position: 'absolute',
                                            zIndex: 10,
                                        }}>
                                            <TextI18n style={{
                                                color: '#fff',
                                                fontSize: 25,
                                                fontFamily: 'Montserrat_Bold',
                                            }}>
                                                tickets.scanned
                                            </TextI18n>
                                        </View>}
                                        <View style={{
                                            borderColor: '#FFE5EC',
                                            borderRadius: 100,
                                            borderWidth: 7,
                                            backgroundColor: '#FFE5EC',
                                            margin: 10,
                                            marginRight: 10,
                                        }}>
                                            <Icon
                                                name="ticket"
                                                type="MaterialCommunityIcons"
                                                style={{ color: commonColor.brandStyle, fontSize: 30 }}
                                            />
                                        </View>
                                        <View style={{ flex: 1, padding: 5, marginRight: 5 }}>
                                            <View style={{
                                                flex: 1,
                                                flexDirection: 'row',
                                                alignItems: 'center',
                                                justifyContent: 'space-between',
                                            }}>
                                                <TextH2t style={{ fontSize: 15 }}>
                                                    {item.title ? (item.title.length > 22) ? ((item.title.substring(0, 22 - 3)) + '...') : item.title : ''}
                                                </TextH2t>
                                                <TextH2t style={{ fontSize: 13 }}>
                                                    {item.date ? item.date : ''}
                                                </TextH2t>
                                            </View>
                                            <View style={{
                                                flex: 1,
                                                flexDirection: 'row',
                                                alignItems: 'center',
                                                justifyContent: 'space-between',
                                            }}>
                                                <View style={{ flexDirection: 'row' }}>
                                                    <Icon type="FontAwesome5" name="music"
                                                          style={{ fontSize: 16, color: '#b3b5bb', paddingRight: 5 }}/>
                                                    <TextH2t style={{ color: '#b3b5bb', fontSize: 13 }}>Techno</TextH2t>
                                                </View>
                                                <TextH2t style={{ color: '#b3b5bb', fontSize: 13 }}>
                                                    {item.hour ? item.hour : ''}
                                                </TextH2t>
                                            </View>
                                        </View>
                                    </View>
                                </TouchableOpacity>)}
                            keyExtractor={(index) => {return index.uuid;}}
                        />

                    </View>) : (
                        <View>
                            <Spacer size={100}/>
                            <TextI18n style={{ fontSize: 30, textAlign: 'center', fontFamily: 'Montserrat_Bold' }}>
                               tickets.noTickets
                            </TextI18n>
                            <TextI18n style={{ fontSize: 15, textAlign: 'center' }}>
                                tickets.noTicketsInfo
                            </TextI18n>
                        </View>
                    )}
                <Spacer size={20}/>
            </Content>
        </ImageBackground>
    </Container>
)
Example #22
Source File: HomeHeadDivision.js    From id.co.moonlay-eworkplace-mobile with MIT License 4 votes vote down vote up
render() {
    const loadings = this.props.loading
      return(
          <SafeAreaView style={{backgroundColor:'#F9FCFF'}}>
            <ScrollView
              alwaysBounceVertical={true} 
              refreshControl={
                <RefreshControl refreshing={this.state.refreshing} 
              onRefresh={this.onRefresh} />
            }>
              <View style={{marginLeft:'5%'}}>
                <Text style={styles.textUsername}>Hi, {this.state.firstname}!</Text>
                <View style={styles.view1}>
                <View style={{width:20, height:'100%', alignItems:'center'}}>
                  <FontAwesome5 name='map-marker-alt' size={16} color='#E74C3C' style={{marginTop:3}}/>
                </View>
                <View style={{width:'100%', height:20, justifyContent:'center'}}>
                  <Text style={styles.textLocation}>{this.state.Location}</Text>
                </View> 
                </View>
              </View>
              <View style={{ flex:1,}}>
                <Card containerStyle={styles.card4}>
                  <Text style={styles.textHour}>
                    {this.state.hour}
                  </Text>
                  <Text style={styles.textDay}>
                    {this.state.day}, {this.state.monthYear}
                  </Text>
                  <View>
                    <TouchableOpacity style={[this.props.clockin_status === false ? styles.buttonClockIn : styles.buttonClockOut]} onPress={this.ButtonCheck}>
                      <Text style={styles.textClockin}>{this.state.textButton}</Text>
                    </TouchableOpacity>
                    <Text style={[styles.textStatus]}>{this.props.status_Checkin}</Text>
                  </View>
                </Card>
              </View>

              <View style={{flexDirection:'row', flex:0.5, marginTop:36}}>
                <View style={{width:'50%', flex:1}}>
                  <Card containerStyle={styles.card4}>
                    <TouchableOpacity style={{flexDirection:'row', padding:0}} onPress={this.movetoWFH}>
                    <WFH width={35} height={35}/>  
                    <Text style={styles.text1}>Work From {'\n'}Home</Text>
                    </TouchableOpacity>
                  </Card>
                </View>
                <View style={{width:'50%', flex:1}}>
                  <Card containerStyle={styles.card4}>
                    <TouchableOpacity style={{flexDirection:'row', paddingBottom:3}} onPress={this.movetoWAC}>
                    <Buildings width={35} height={35}/> 
                    <Text style={styles.text1}>Work At {'\n'}Client Office</Text>
                    </TouchableOpacity>
                  </Card>
                </View>            
              </View> 

              <View style={{ flex:3, paddingBottom:'5%'}}>
              <Text style={styles.textDashboard}>Dashboard</Text>
                <Card containerStyle={styles.cardApprove}>
                  <TouchableOpacity style={styles.baseTouchAble} onPress={this.movetoApprovalPage}>
                    <Text style={styles.text2}>Approval</Text>
                    <Text style={styles.text3}>{this.state.textApproved}</Text>
                    <View style={styles.view2InCard1}>
                      <View style={{flex:3, flexDirection:'row'}}>
                      </View>
                      <View style={{flex:3}}>
                      <Text style={styles.textViewDetails}>View Details</Text>
                      </View>                     
                    </View> 
                  </TouchableOpacity>
                </Card>

                <Card containerStyle={styles.card1}>
                  <TouchableOpacity style={styles.baseTouchAble} onPress={this.movetoMeetingsPage}>
                    <Text style={styles.text2}>Meeting</Text>
                    <Text style={styles.text3}>Scrum Meetings</Text>
                    <View style={styles.viewInCard1}>
                        <FontAwesome5 name='map-marker-alt' size={16} color='#505050'/>
                        <Text style={styles.text4}>Meeting Room A, Moonlay Office</Text>                  
                    </View>
                    <Image style={{width: '100%'}} source={require('../../image/line.png')}/>
                    <View style={styles.view2InCard1}>
                      <View style={{flex:3, flexDirection:'row'}}>
                        <FontAwesome5 name='clock' size={16} color='#505050' style={{marginTop:1}}/>
                        <Text style={styles.text5}>02.00 PM</Text>
                      </View>
                      <View style={{flex:3}}>
                      <Text style={styles.textViewDetails}>View Details</Text>
                      </View>                     
                    </View> 
                  </TouchableOpacity>
                </Card>

                <Card containerStyle={styles.card2}>
                  <TouchableOpacity style={styles.baseTouchAble}>
                    <Text style={styles.text2}>Ongoing Task</Text>
                    <View style={styles.viewInCard2}>
                      <FontAwesome5 name='circle' size={8} color='#505050' solid/>
                      <Text style={styles.text6}>Task 01 - 25 Feb 2020</Text>
                    </View>
                    <View style={styles.viewInCard2}>
                      <FontAwesome5 name='circle' size={8} color='#505050' solid/>
                      <Text style={styles.text6}>Task 01 - 25 Feb 2020</Text>
                    </View>
                    <View style={styles.viewInCard2}>
                      <FontAwesome5 name='circle' size={8} color='#505050' solid/>
                      <Text style={styles.text6}>Task 01 - 25 Feb 2020</Text>
                    </View>
                    <View style={{flexDirection:'row'}}>
                      <View style={{flex:3}}>
                        <Text style={styles.text6}>...</Text>
                      </View>
                      <View style={{flex:3}}>
                        <Text style={styles.textViewDetails}>View Details</Text>
                      </View>
                    </View>
                  </TouchableOpacity>
                </Card>
                
                <Card containerStyle={styles.card3}>
                  <TouchableOpacity style={styles.baseTouchAble} onPress={this.movetoTaskDonePage}>
                  <Text style={styles.text2}>Task Done</Text>
                    <View style={styles.viewInCard2}>
                      <FontAwesome5 name='circle' size={8} color='#505050' solid/>
                      <Text style={styles.text6}>Task 01 - 25 Feb 2020</Text>
                    </View>
                    <View style={styles.viewInCard2}>
                      <FontAwesome5 name='circle' size={8} color='#505050' solid/>
                      <Text style={styles.text6}>Task 01 - 25 Feb 2020</Text>
                    </View>
                    <View style={styles.viewInCard2}>
                      <FontAwesome5 name='circle' size={8} color='#505050' solid/>
                      <Text style={styles.text6}>Task 01 - 25 Feb 2020</Text>
                    </View>
                    <View style={{flexDirection:'row'}}>
                      <View style={{flex:3}}>
                        <Text style={styles.text6}>...</Text>
                      </View>
                      <View style={{flex:3}}>
                        <Text style={styles.textViewDetails}>View Details</Text>
                      </View>
                    </View>
                  </TouchableOpacity>
                </Card>        
          </View>
              <Loading visible={loadings === true ? true : false}/>               
            </ScrollView>
          </SafeAreaView>
        );
      }
Example #23
Source File: EventsListing.js    From expo-ticket-app with MIT License 4 votes vote down vote up
EventsListing = ({ loading, events, reFetch }) => {

    const onPress = index => Actions.eventView({ match: { params: { id: String(index) } } });

    return (
        <Container style={{ backgroundColor: commonColor.backgroundColor }}>
            <StatusBar style="light"/>
            <TextI18n style={{ color: '#ffffff', fontSize: 30, margin: 50, marginBottom: 10, marginLeft: 10 }}>
                events.title
            </TextI18n>
            <Content padder refreshControl={(
                <RefreshControl
                    refreshing={loading}
                    onRefresh={reFetch}
                    title="Pull to refresh"
                    tintColor="#fff"
                    titleColor="#fff"
                    colors={['#000', '#fff', '#000']}
                />
            )}>
                <FlatList
                    data={events}
                    renderItem={({ item, index }) => (
                        <TouchableOpacity onPress={() => onPress(index)} style={{ flex: 1 }}>
                            <View style={{
                                flex: 1,
                                flexDirection: 'column',
                                justifyContent: 'center',
                            }}>
                                <View style={{
                                    shadowColor: '#000',
                                    shadowOffset: {
                                        width: 0,
                                        height: 6,
                                    },
                                    shadowOpacity: 0.39,
                                    shadowRadius: 8.30,
                                    elevation: 13,
                                    borderRadius: 5,
                                    position: 'absolute',
                                    backgroundColor: commonColor.brandStyle,
                                    width: 100,
                                    height: 34,
                                    top: 150 + ((deviceWidth > 400) ? 40 : 20),
                                    right: 40,
                                    zIndex: 1000,
                                    alignItems: 'center',
                                    justifyContent: 'center',
                                }}>
                                    <TextH2t style={{ color: '#ffffff', fontSize: 18 }}>
                                        {item.price ? item.price + ' $' : 'Free'}
                                    </TextH2t>
                                </View>
                                <View style={{
                                    shadowColor: '#000',
                                    shadowOffset: {
                                        width: 0,
                                        height: 3,
                                    },
                                    shadowOpacity: 0.29,
                                    shadowRadius: 4.65,
                                    elevation: 8,
                                    borderRadius: 5,
                                    flex: 1,
                                }}>
                                    <Image
                                        source={{ uri: item.image ? item.image : '' }}
                                        style={{
                                            width: '100%',
                                            aspectRatio: 1.85,
                                            resizeMode: 'stretch',
                                            borderRadius: (Platform.OS === 'ios') ? 5 : 10,
                                        }}
                                    />
                                </View>
                                <View style={{ flex: 1, padding: 10 }}>
                                    <TextH2t style={{ color: '#ffffff', fontSize: 16 }}>
                                        {item.date}
                                    </TextH2t>
                                    <TextH2t style={{ color: '#ffffff', fontSize: 23, fontFamily: 'Montserrat_Bold' }}>
                                        {item.title}
                                    </TextH2t>
                                    <TextH2t style={{ color: '#b3b5bb', fontSize: 13 }}>
                                        {item.hour}
                                    </TextH2t>
                                    <View style={{
                                        flexDirection: 'row',
                                        alignItems: 'center',
                                        justifyContent: 'space-between',
                                    }}>
                                        <View style={{ flexDirection: 'row' }}>
                                            <TextH2t style={{ color: '#b3b5bb', fontSize: 13 }}># Techno</TextH2t>
                                        </View>
                                        <View style={{ flexDirection: 'row', justifyContent: 'center' }}>
                                            <Icon type="FontAwesome" name="ticket"
                                                  style={{ fontSize: 17, color: '#b3b5bb', paddingRight: 5 }}/>
                                            <TextH2t style={{
                                                color: '#b3b5bb',
                                                fontSize: 13,
                                            }}>{item.tickets > 0 ? `${item.tickets} ${i18n.t('events.available')}` : i18n.t('events.full')}</TextH2t>
                                        </View>
                                    </View>
                                </View>
                            </View>
                        </TouchableOpacity>
                    )}
                    keyExtractor={(item, index) => (`list-item-${index}`)}
                />
                <Spacer size={20}/>
            </Content>
        </Container>
    );
}
Example #24
Source File: UserProfileScreen.js    From SocialApp-React-Native with MIT License 4 votes vote down vote up
UserProfileScreen = (props) => {
    const { route } = props;
    const loggedInUserId = useSelector(state => state.auth.user._id);
    const allUsers = useSelector(state => state.users.allUsers);
    const loggedInUser = allUsers.filter(u => u._id === loggedInUserId)[0];

    let userId;

    if(route.params && route.params.userId){
        userId = route.params.userId;
    } else {
        userId = useSelector(state => state.auth.user._id);
    }
    
    const users = useSelector(state => state.users.allUsers);
    const posts = useSelector(state => state.posts.allPosts);
    const currUser = users.filter(u => u._id === userId)[0];
    const currUserPosts = posts.filter(p => p.postedBy._id === userId);
    
    const [isRefreshing,setIsRefreshing] = useState(false);
    const [isLoading,  setIsLoading] = useState(false);
    const [isFollowLoading,  setIsFollowLoading] = useState(false);
    const [imageUri, setImageUri] = useState('');
    
    const dispatch = useDispatch();


    const loadUsers = useCallback(async () => {
        setIsRefreshing(true);
        try {
            await dispatch(usersActions.fetchUsers());
            await dispatch(postsActions.fetchPosts());
        } catch (err) {
            console.log(err);
        }
        setIsRefreshing(false);
    }, [dispatch, setIsLoading]);

    const onImageErrorHandler = () => {
        setImageUri(ENV.defaultImageUri)
    }


    const checkFollow = (userId) => {
        const isFollowed = loggedInUser.following.filter(f => f._id === userId).length !== 0;
        return isFollowed;
    }

    const followUserHandler = async () => {
        let user = {...currUser};
        delete user.created;
        delete user.followers;
        delete user.following;
        // setIsFollowLoading(true);
        
        if(checkFollow(user._id)){
            showMessage({
                message: `Your have unfollowed ${user.name}.`,
                type: "warning",
                duration: 3000,
                icon: { icon: "warning", position: 'left' }
            });
            await dispatch(usersActions.unfollowUser(user))
        } else {
            showMessage({
                message: `Your are now following ${user.name}.`,
                type: "success",
                duration: 3000,
                icon: { icon: "success", position: 'left' }
            });
            await dispatch(usersActions.followUser(user))
        }
        // setIsFollowLoading(false);
    }







    const renderSectionOne = () => {
        if(currUserPosts.length === 0 ){
            return(
                <View style={{ flex: 1, justifyContent: 'center', alignItems: 'center', borderTopColor: '#c2c2c2', borderTopWidth: 1 }} >   
                    <Text style={{ fontSize: 20, fontWeight: 'bold', marginTop: 25 }} >No Posts</Text>
                    { currUser._id === loggedInUserId && (
                        <Button
                            style={{ backgroundColor: Colors.brightBlue, padding: 10, borderRadius: 25, marginTop: 15 }}
                            onPress={() => props.navigation.navigate('AddPost')}
                        >
                            <Text style={{ color: '#fff' }} >Create Post</Text>
                        </Button>
                    ) }
                    
                </View>
            )
        }
        return currUserPosts.map((post, index) => {
            return (
                <TouchableOpacity 
                    key={index}
                    onPress={() => props.navigation.navigate('UserPosts', { userId: userId, postIndex: index, fromUserProfile: true })}
                >
                    <View  style={[{ width: (width) / 3 }, { height: (width) / 3 }, { marginBottom: 2 }, index % 3 !== 0 ? { paddingLeft: 2 } : { paddingLeft: 0 }]}>
                        <Image 
                            style={{
                                flex: 1,
                                alignSelf: 'stretch',
                                width: undefined,
                                height: undefined,
                                backgroundColor: '#c2c2c2'
                            }}
                            source={
                                post.updated ? (
                                    { uri: `${ENV.apiUrl}/post/photo/${post._id}?${new Date(post.updated)}` }
                                ) : (
                                    { uri: `${ENV.apiUrl}/post/photo/${post._id}` }
                                )
                            }
                        />
                    </View>
                </TouchableOpacity>
            )
        })
    }

    const renderSection = () => {
            return (
                <View style={{ flexDirection: 'row', flexWrap: 'wrap' }}>
                    {renderSectionOne()}
                </View>
            )
    }


    if(isLoading){
        return (
            <View style={styles.centered} >
                <ActivityIndicator size='large' color={Colors.primary} />
            </View>
        );
    }


    let TouchableComp = TouchableOpacity;
    if(Platform.OS === 'android' && Platform.Version >= 21){
        TouchableComp = TouchableNativeFeedback;
    }


    return (
        <Container style={styles.container} >
            <Content 
                refreshControl={
                    <RefreshControl refreshing={isRefreshing} onRefresh={loadUsers} /> 
                } 
            >
                <View style={{ paddingTop: 20 }}>
                    {/** User Photo Stats**/}
                    <View style={{ flexDirection: 'row' }}>
                        {/**User photo takes 1/3rd of view horizontally **/}
                        <View
                            style={{ flex: 1, alignItems: 'center', justifyContent: 'flex-start' }}>
                            <Image 
                                source={{ uri: imageUri || `${ENV.apiUrl}/user/photo/${currUser._id}?${new Date(currUser.updated)}` }}
                                onError={onImageErrorHandler}
                                style={{ width: 75, height: 75, borderRadius: 37.5, backgroundColor: "#c2c2c2" }}
                            />
                        </View>
                        {/**User Stats take 2/3rd of view horizontally **/}
                        <View style={{ flex: 3 }}>
                            {/** Stats **/}
                            <View
                                style={{
                                    flexDirection: 'row',
                                    justifyContent: 'space-around',
                                    alignItems: 'flex-end'
                                }}
                            >
                                <View style={{ alignItems: 'center' }}>
                                    <TouchableComp
                                        background={ Platform.OS === 'ios' ? undefined : TouchableNativeFeedback.Ripple('#c2c2c2', true) }
                                        onPress={() => props.navigation.navigate(
                                            'UserPosts', 
                                            { userId: userId, postIndex: 0, fromUserProfile: true }
                                        )}
                                    >
                                        <View style={{ justifyContent: 'center', alignItems: 'center' }} >
                                            <Text style={{ fontSize: 18 }} >{currUserPosts.length}</Text>
                                            <Text style={{ fontSize: 12, color: 'grey' }}>Posts</Text>
                                        </View>
                                    </TouchableComp>
                                </View>

                                <View style={{ alignItems: 'center' }}>
                                    <TouchableComp
                                        background={ Platform.OS === 'ios' ? undefined : TouchableNativeFeedback.Ripple('#c2c2c2', true) }
                                        onPress={() => props.navigation.navigate(
                                            'UserStats',
                                            { activeTab: 0, currUser: currUser }
                                        )}
                                    >
                                        <View style={{ justifyContent: 'center', alignItems: 'center' }} >
                                            <Text style={{ fontSize: 18 }} >{currUser.followers.length}</Text>
                                            <Text style={{ fontSize: 12, color: 'grey' }}>Followers</Text>
                                        </View>
                                    </TouchableComp>
                                </View>

                                <View style={{ alignItems: 'center' }}>
                                    <TouchableComp
                                        background={ Platform.OS === 'ios' ? undefined : TouchableNativeFeedback.Ripple('#c2c2c2', true) }
                                        onPress={() => props.navigation.navigate(
                                            'UserStats',
                                            { activeTab: 1, currUser: currUser }
                                        )}
                                    >
                                        <View style={{ justifyContent: 'center', alignItems: 'center' }} >
                                            <Text style={{ fontSize: 18 }} >{currUser.following.length}</Text>
                                            <Text style={{ fontSize: 12, color: 'grey' }}>Following</Text>
                                        </View>
                                    </TouchableComp>
                                </View>
                            </View>
                            {/**
                             * Edit profile and Settings Buttons **/}

                            { userId === loggedInUserId ? (
                                <View style={{ alignItems: 'flex-start', paddingTop: 10 }}>
                                    <View
                                        style={{ flexDirection: 'row' }}>
                                        <Button
                                            onPress={() => props.navigation.navigate('EditProfile')}
                                            bordered
                                            dark
                                            style={{ flex: 1, marginLeft: 10, marginRight: 10, justifyContent: 'center', height: 30 }}
                                        >
                                            <Text>Edit Profile</Text>
                                        </Button>
                                    </View>
                                </View>
                            ) : (
                                <View style={{ flexDirection: 'row', alignItems: 'flex-start', paddingTop: 10 }}>
                                    <TouchableOpacity
                                        style={{ flexDirection: 'row' }}>
                                        <Button 
                                            onPress={followUserHandler}
                                            bordered 
                                            dark
                                            style={{ flex: 2, marginLeft: 10, marginRight: 10, justifyContent: 'center', height: 30 }}
                                        >
                                            { checkFollow(currUser._id) ? (
                                                <>
                                                    { isFollowLoading ? (
                                                        <ActivityIndicator size="small" color="#fff" />
                                                    ) : (
                                                        <Text style={{ color: 'black' }} >Unfollow</Text>
                                                    ) }
                                                </>
                                            ) : (
                                                <>
                                                    { isFollowLoading ? (
                                                        <ActivityIndicator size="small" color="#fff" />
                                                    ) : (
                                                        <Text style={{ color: 'black' }} >Follow</Text>
                                                    ) }
                                                </>
                                            ) }
                                        </Button>
                                    </TouchableOpacity>
                                </View>
                            ) }
                            {/**End edit profile**/}
                        </View>
                    </View>

                    <View style={{ paddingBottom: 10, paddingTop: 10 }}>
                        <View style={{ paddingHorizontal: 10 }} >
                            <Text style={{ fontWeight: 'bold', fontSize: 18 }}>
                                {currUser.name + " "} 
                                {
                                    VerifiedUser.verifiedUsersId.includes(currUser._id) && <Octicons name="verified" size={20} color={Colors.brightBlue} />
                                }
                            </Text>
                            
                            { currUser.about && (
                                <Text>{currUser.about} </Text>
                            ) }
                            <Text>{currUser.email}</Text>
                        </View>
                    </View>
                </View>


                <View>
                    {renderSection()}
                </View>
            </Content>
        
        </Container >
    );
}
Example #25
Source File: ChatScreen.js    From app with GNU General Public License v3.0 4 votes vote down vote up
ChatScreen = ({navigation}) => {
	const [searchQuery, setSearchQuery] = useState('');
	const {user,updateMessages,messages,token,queue} = useContext(GlobalContext);
	const [refreshing,setRefreshing] = useState(false);

	const search = () => {
		console.log('in search frands');
	};
	
	//?Todo On first login it wont get messages from global queue, so pass it from the messaging
	//?Todo screen only

	console.log(messages,"messages from gs");

	const dateFunc = (dynamicDate) => {
		const d = new Date(dynamicDate);
		const today = new Date();

		const diff = parseInt(((today - d)/60000));

		if(diff>0 && diff<60){
			return `${diff} mins`;
		}
		else if(diff > 60 && diff < 1440){
			return `${parseInt(diff/60)} hours`
		}
		else if(diff > 1440 && diff < 10800){
			return `${parseInt(diff/1440)} days`
		}
		else if(diff > 10080 && diff < 43200){
			return `${parseInt(diff/10080)} weeks`
		}
		else if(diff > 43200 && diff < 518400){
			return `${parseInt(diff/43200)} months`
		}
		else{
			return `${diff} secs`
		}
	}

	useEffect(() => {
		if(messages.length === 0 || refreshing){
			console.log("in")
			axios.get(`${userApiUrl}/messages/getMessages`,{
				headers: {
					Authorization: "Bearer " + token,
				}
			})
			.then(async (res) => {
				console.log(res.data,"from local messages");
				updateMessages(res.data);
				setRefreshing(false);
				await AsyncStorage.setItem("messages",JSON.stringify(res.data));
			}).catch((err) => {
				console.log(err,"err");
				setRefreshing(false);
				if (Platform.OS === 'android') {
					ToastAndroid.show("Network Error", ToastAndroid.SHORT);
				}
			})
		}
	},[refreshing])

	const onRefresh = useCallback(() => {
    	setRefreshing(true);
  	}, []);

	const renderer = ({item}) => {
		const pressChatBox = () => {
			navigation.navigate("MessagingScreen",{
				item
			})
		}

		return (
			<View
				key={item._id}
				style={{
					flexDirection: 'column',
					marginVertical:"5%",
					height: '10%',
					marginBottom: "12%"
				}}>
			
					<TouchableOpacity onPress={pressChatBox}
						style={{
							flexDirection: 'row',
						}}>
							
						<Image
							source={{uri: item.to._id !== user._id ? item.to.photo : item.user.photo}}
							style={{
								borderRadius: 20,
								left: 10,
								width: 50,
								height: 50,
							}}
						/>

						<View
							style={{
								flex: 1,
								
							}}>
							<View
								style={{
									flexDirection: 'row',
								}}>
								<Text style={{
									...styles.options,
									marginLeft:30
								}}>
									{item.to._id !== user._id ? 
										item.to.username.length > 30
										? item.to.username.substring(0, 30) +
										'...'
										: item.to.username
										: 
										(
										item.user.username.length > 30
										? item.user.username.substring(0, 30) +
										'...'
										: item.user.username
										)
									}
								</Text>
							</View>
							<View
								style={{
									maxWidth: '80%',
									flexDirection: 'row',
								}}>
									<View style={{
										width:"90%"
									}}>
											<Text
									style={{
										...styles.options,
										fontSize: 14,
										marginLeft:30,
										marginTop: 2,
										fontFamily: 'NotoSans-Regular',
									}}>
									{`${item.chat[item.chat.length-1].user._id === user._id ? "You" : item.chat[item.chat.length-1].user.username} shared ${item.chat[item.chat.length-1].message.trackName}`}.
								</Text>		
									</View>

								
								<Text
									style={{
										...styles.options,
										opacity:0.75,
										marginTop: -25,
										marginLeft:10,
									}}>
									{dateFunc(item.chat[item.chat.length-1].messageSentAt)}
								</Text>
							</View>
						</View>
				</TouchableOpacity>
			</View>
		)
	}

	return (
		<LinearGradientComp
			bgcolors={{
				colorOne: "rgb(15, 15, 15)",
				colorTwo: "rgb(15, 15, 15)",
			}}>
			<ScrollView 
				 refreshControl={
					<RefreshControl
						refreshing={refreshing}
						onRefresh={onRefresh}
					/>
        		}
			>

				<Text
					style={{
						marginTop:"15%",
						fontSize: 26,
						color: 'white',
						marginBottom: 10,
						marginLeft: 20,
						letterSpacing: 0,
						fontFamily: 'NotoSans-Regular',
					}}>
					Messages
				</Text>
				<View style={{
					marginBottom:20
				}}>
					{
						messages.length > 0 ? (
							<FlatList
								keyExtractor={(item) => item._id}
								data={messages}
								renderItem={renderer}
								showsVerticalScrollIndicator={false}
							/>
						)
						:(
							<>
								<FillerContent extraStyles={true} text={"No messages to Show"} />
							</>
						)
					}
				</View>
			</ScrollView>
			{queue && queue.length > 0 ? <MiniPlayer nav={navigation} /> : null}
		</LinearGradientComp>
	);
}
Example #26
Source File: index.js    From real-frontend with GNU General Public License v3.0 4 votes vote down vote up
PostsList = ({
  theme,
  navigation,
  authUser,
  feedRef,
  postsFeedGet,
  postsFeedGetRequest,
  postsFeedGetMoreRequest,
  usersStoriesGet,
  usersStoriesGetRequest,
  postsShareRequest,
  handleEditPress,
  postsArchiveRequest,
  postsRestoreArchivedRequest,
  postsFlag,
  postsFlagRequest,
  postsDeleteRequest,
  postsAnonymouslyLikeRequest,
  postsOnymouslyLikeRequest,
  postsDislikeRequest,
  usersGetFollowedUsersWithStories,
  usersGetFollowedUsersWithStoriesRequest,
  postsCreateRequest,
  postsCreateIdle,
  postsCreateQueue,
  handleProfilePress,
  layoutPostsListItem,
  layoutPostsListItemSuccess,
  layoutPostsListScroll,
  layoutPostsListScrollSuccess,
}) => {
  const styling = styles(theme)
  const { t } = useTranslation()

  const scroll = ScrollHelper({
    navigation,
    postsFeedGet,
    postsFeedGetMoreRequest,
    layoutPostsListScrollSuccess,
    usersStoriesGet,
    usersGetFollowedUsersWithStories,
    postsFeedGetRequest,
    usersStoriesGetRequest,
    usersGetFollowedUsersWithStoriesRequest,
  })

  return (
    <View style={styling.root}>
      <NativeError
        handleCancelPress={() => {}}
        titleText={t('All good!')}
        messageText={t('This post has been flagged as inappropriate')}
        actionText={t('Done')}
        status={postsFlag.status}
        triggerOn="success"
      />

      <FlatList
        ref={feedRef}
        keyExtractor={item => item.postId}
        data={([
          { postId: 'story' },
          {
            postId: 'uploading',
            postsCreateQueue,
          },
          ...path(['data'])(postsFeedGet),
          { postId: 'loading' },
        ])}
        onScroll={scroll.handleScrollChange}
        scrollEventThrottle={500}
        refreshControl={(
          <RefreshControl
            tintColor={theme.colors.border}
            onRefresh={scroll.handleRefresh}
            refreshing={scroll.refreshing}
          />
        )}
        renderItem={({ item: post, index }) => {
          if (post.postId === 'story') {
            return (
              <StoriesComponent
                authUser={authUser}
                usersGetFollowedUsersWithStories={usersGetFollowedUsersWithStories}
                usersStoriesGet={usersStoriesGet}
              />
            )
          }

          if (post.postId === 'uploading') {
            return (
              <View style={styling.uploading}>
                {Object.entries(post.postsCreateQueue).map(([key, post]) => (
                  <UploadingComponent
                    key={key}
                    post={post}
                    postsCreateRequest={postsCreateRequest}
                    postsCreateIdle={postsCreateIdle}
                  />
                ))}
              </View>
            )
          }

          if (post.postId === 'loading') {
            if (path(['status'])(postsFeedGet) === 'loading' && !path(['data', 'length'])(postsFeedGet)) {
              return null
            }
            return null
          }

          return (
            <PostComponent
              authUser={authUser}
              post={post}
              handleEditPress={handleEditPress}
              postsArchiveRequest={postsArchiveRequest}
              postsRestoreArchivedRequest={postsRestoreArchivedRequest}
              postsFlagRequest={postsFlagRequest}
              postsDeleteRequest={postsDeleteRequest}
              postsShareRequest={postsShareRequest}
              postsAnonymouslyLikeRequest={postsAnonymouslyLikeRequest}
              postsOnymouslyLikeRequest={postsOnymouslyLikeRequest}
              postsDislikeRequest={postsDislikeRequest}
              handleProfilePress={handleProfilePress}
              onMeasure={layoutPostsListItemSuccess}
              scrollPosition={layoutPostsListScroll.data.y}
              priorityIndex={index}
            />
          )
        }}
        ListFooterComponent={scroll.loadingmore ? ActivityIndicator : null}
        ListFooterComponentStyle={styling.loading}
      />

    </View>
  )
}
Example #27
Source File: BigList.jsx    From react-native-big-list with Apache License 2.0 4 votes vote down vote up
/**
   * Render.
   * @returns {JSX.Element}
   */
  render() {
    // Reduce list properties
    const {
      data,
      keyExtractor,
      inverted,
      horizontal, // Disabled
      placeholder,
      placeholderImage,
      placeholderComponent,
      sections,
      initialScrollIndex,
      columnWrapperStyle,
      renderHeader,
      renderFooter,
      renderSectionHeader,
      renderItem,
      renderSectionFooter,
      renderScrollViewWrapper,
      renderEmpty,
      renderAccessory,
      itemHeight,
      footerHeight,
      headerHeight,
      sectionHeaderHeight,
      sectionFooterHeight,
      insetTop,
      insetBottom,
      actionSheetScrollRef,
      stickySectionHeadersEnabled,
      onEndReached,
      onEndReachedThreshold,
      onRefresh,
      refreshing,
      ListEmptyComponent,
      ListFooterComponent,
      ListFooterComponentStyle,
      ListHeaderComponent,
      ListHeaderComponentStyle,
      hideMarginalsOnEmpty,
      hideFooterOnEmpty,
      hideHeaderOnEmpty,
      ScrollViewComponent,
      ...props
    } = this.props;

    const wrapper = renderScrollViewWrapper || ((val) => val);
    const handleScroll =
      stickySectionHeadersEnabled && Platform.OS === "web"
        ? Animated.event(
            [{ nativeEvent: { contentOffset: { y: this.scrollTopValue } } }],
            {
              listener: (event) => this.onScroll(event),
              useNativeDriver: false,
            },
          )
        : this.onScroll;

    const defaultProps = {
      refreshControl:
        onRefresh && !this.props.refreshControl ? (
          <RefreshControl refreshing={refreshing} onRefresh={onRefresh} />
        ) : null,
      contentContainerStyle: {
        flexDirection: "row",
        flexWrap: "wrap",
        maxWidth: "100%",
      },
    };

    const overwriteProps = {
      ref: (ref) => {
        this.scrollView.current = ref;
        if (actionSheetScrollRef) {
          actionSheetScrollRef.current = ref;
        }
      },
      onScroll: handleScroll,
      onLayout: this.onLayout,
      onMomentumScrollEnd: this.onMomentumScrollEnd,
      onScrollEndDrag: this.onScrollEnd,
    };

    const scrollViewProps = {
      ...defaultProps,
      ...props,
      ...overwriteProps,
    };

    // Content container style merge
    scrollViewProps.contentContainerStyle = mergeViewStyle(
      props.contentContainerStyle,
      defaultProps.contentContainerStyle,
    );

    const ListScrollView = ScrollViewComponent || ScrollView;

    const scrollView = wrapper(
      <ListScrollView {...scrollViewProps}>
        {this.renderItems()}
      </ListScrollView>,
    );

    const scrollStyle = mergeViewStyle(
      {
        flex: 1,
        maxHeight: Platform.select({ web: "100vh", default: "100%" }),
      },
      this.getBaseStyle(),
    );

    return (
      <View style={scrollStyle}>
        {scrollView}
        {renderAccessory != null ? renderAccessory(this) : null}
      </View>
    );
  }
Example #28
Source File: SettingsScreen.js    From hugin-mobile with GNU Affero General Public License v3.0 4 votes vote down vote up
render() {

      const { t } = this.props;
        return(
            <View style={{
                backgroundColor: this.props.screenProps.theme.backgroundColour,
                flex: 1
            }}>
                <ScrollView
                    style={{
                        backgroundColor: this.props.screenProps.theme.backgroundColour,
                        flex: 1,
                        marginTop: 50,
                    }}
                    refreshControl={
                        <RefreshControl
                            refreshing={this.state.refreshing}
                            onRefresh={this.refresh}
                            title={t('updatingNodes')}
                        />
                    }
                >

                <View style={{
                    backgroundColor: this.props.screenProps.theme.backgroundColour,
                    marginHorizontal: 20,
                }}>
                <Text style={{
                    fontSize: 20,
                    textAlign: 'center',
                    color: this.props.screenProps.theme.primaryColour,
                }}>
                    {t('useCustomNode')}
                </Text>
                <Text style={{
                    fontSize: 12,
                    color: this.props.screenProps.theme.primaryColour,
                    textAlign: 'center',
                    marginBottom: 5
                }}>
                    {t('customNodeFormat')}
                </Text>
                </View>
                <Input
                    ref={this.state.input}
                    containerStyle={{
                        width: '100%',
                    }}
                    inputContainerStyle={{
                        backgroundColor: 'rgba(0,0,0,0.2)',
                        borderWidth: 0,
                        borderColor: 'transparent',
                        borderRadius: 15,
                        width: '100%',
                        height: 40,
                        padding: 15
                    }}
                    inputStyle={{
                        color: this.props.screenProps.theme.primaryColour,
                        fontFamily: 'Montserrat-Regular',
                        fontSize: 15
                    }}
                    placeholder={this.state.selectedNode}
                    onSubmitEditing={async (e) => {
                        // if (this.props.onChange) {
                        //     this.props.onChange(text);
                        // }
                          let text = e.nativeEvent.text;
                          text = text.split(':');
                          let node = {url: text[0], port: text[1], ssl: text[2]};

                          this.swapNode(node);
                          // toastPopUp('Sending message: ' + text + " to " + this.state.address + " with msg key " + this.state.paymentID);
                          // let updated_messages = await getMessages();
                          // let temp_timestamp = Date.now();
                          // updated_messages.push({
                          //     conversation: this.state.address,
                          //     type: 'sent',
                          //     message: checkText(text),
                          //     timestamp: temp_timestamp
                          // });
                          //
                          // this.setState({
                          //   messages: updated_messages
                          // })
                          // this.state.input.current.clear();
                          //
                          // let success = await sendMessage(checkText(text), this.state.address, this.state.paymentID);
                          // await removeMessage(temp_timestamp);
                          // if (success) {
                          // let updated_messages = await getMessages();
                          //
                          //   this.setState({
                          //     messages: updated_messages
                          //   })
                          //   // this.state.input.current.clear();
                          // }
                    }}
                    onChangeText={(text) => {
                        if (this.props.onChange) {
                            this.props.onChange(text);
                        }
                    }}
                    errorMessage={this.props.error}
                />
                <Text style={{
                    fontSize: 20,
                    color: this.props.screenProps.theme.primaryColour,
                    textAlign: 'center'
                }}>
                    {t('or')}
                </Text>
                <View
                style={{
                    marginVertical: 20,
                    marginHorizontal: 20,
                    marginTop: 5
                }}
                >
                    <Button
                        title={t('autoSelectNode')}
                        onPress={async () => {
                          const best_node = await getBestNode();
                          console.log('getBestNode', best_node);
                            this.setState({
                                node: best_node,
                            });
                            this.swapNode(best_node);
                        }}
                        color={this.props.screenProps.theme.buttonColour}
                        titleStyle={{
                            color: this.props.screenProps.theme.primaryColour,
                            fontSize: 13
                        }}
                        type="clear"
                    />

                  </View>

                    {this.state.nodes.length > 0 ?

                        <List style={{
                            backgroundColor: this.props.screenProps.theme.backgroundColour,
                            borderTopWidth: 0
                        }}>
                        <Text style={{
                            fontSize: 20,
                            color: this.props.screenProps.theme.primaryColour,
                            textAlign: 'center',

                        }}>
                            {t('pickNodeList')}
                        </Text>
                        <Text style={{
                            fontSize: 10,
                            color: this.props.screenProps.theme.primaryColour,
                            textAlign: 'center',
                            marginBottom: 5
                        }}>
                            {t('pullToCheck')}
                        </Text>
                            <FlatList
                                style={{marginHorizontal: 20}}
                                extraData={this.state.forceUpdate}
                                data={this.state.nodes}
                                keyExtractor={(item) => item.url + item.port}
                                renderItem={({ item }) => (
                                    <ListItem
                                        title={item.name}
                                        subtitle={`URL: ${item.url + ':' + item.port} Fee: ${item.fee}/tx`}
                                        leftIcon={
                                            item.online == undefined ? <View style={{
                                                width: 5,
                                                height: 5,
                                                alignItems: 'center',
                                                justifyContent: 'center',
                                                backgroundColor: '#555555',
                                                borderRadius: 45
                                            }}>
                                            </View> :
                                            <View style={{
                                                width: 5,
                                                height: 5,
                                                alignItems: 'center',
                                                justifyContent: 'center',
                                                backgroundColor: item.online ? '#33ff33' : '#ff0000',
                                                borderRadius: 45
                                            }}>
                                            </View>
                                        }
                                        titleStyle={{
                                            color: this.state.selectedNode === item.url + ':' + item.port + ":" + item.ssl
                                                ? this.props.screenProps.theme.primaryColour
                                                : this.props.screenProps.theme.slightlyMoreVisibleColour,
                                        }}
                                        subtitleStyle={{
                                            color: this.state.selectedNode === item.url + ':' + item.port + ":" + item.ssl
                                                ? this.props.screenProps.theme.primaryColour
                                                : this.props.screenProps.theme.slightlyMoreVisibleColour,
                                        }}
                                        onPress={async () => {
                                            if (!item.online) {
                                                Alert.alert(
                                                    'Use offline node?',
                                                    'Are you sure you want to attempt to connect to a node which is reporting as offline?',
                                                    [
                                                        {text: 'Yes', onPress: () => {
                                                            this.swapNode(item);
                                                        }},
                                                        {text: 'Cancel', style: 'cancel'},
                                                    ],
                                                );
                                            } else {
                                                this.swapNode(item);
                                            }
                                        }}
                                    />
                                )}
                            />
                        </List> :
                        <View style={{
                            backgroundColor: this.props.screenProps.theme.backgroundColour,
                            marginHorizontal: 20,
                        }}>
                            <Text style={{
                                fontSize: 20,
                                color: this.props.screenProps.theme.primaryColour,
                            }}>
                                {t('noNodes')}
                            </Text>
                        </View>
                    }

                </ScrollView>
            </View>
        );
    }
Example #29
Source File: ExpiryScreen.js    From inventory-management-rn with MIT License 4 votes vote down vote up
ExpiryScreen = ({navigation}) => {
  const [expiryList, setExpiryList] = useState([]);
  // true when waiting for an response from API
  const [isLoading, setIsLoading] = useState(false);
  const [count, setCount] = useState(0);

  const apiFetch = async () => {
    try {
      const auth_key = await AsyncStorage.getItem('auth_key');
      console.log(auth_key);
      fetch('http://chouhanaryan.pythonanywhere.com/api/explist/', {
        method: 'GET',
        headers: {
          Authorization: `Token ${auth_key}`,
        },
      })
        .then(res => res.json())
        .then(data => {
          console.log(data);
          setCount(data.count);
          const list = data.results.map(val => ({
            name: val.Product,
            quantity: val['No. of items'],
            daysLeft: val['Days left'],
          }));
          setExpiryList(list);
        })
        .catch(err => console.log(err));
    } catch (e) {
      console.log(e);
    }
  };
  useEffect(() => {
    console.disableYellowBox = true;
    apiFetch();
  }, []);

  const [refreshing, setRefreshing] = React.useState(false);

  const onRefresh = React.useCallback(() => {
    setRefreshing(true);
    apiFetch();
     setRefreshing(false)
  }, []);
  return (
    <Container style={{backgroundColor: '#F3F9FB'}}>
      <Text style={{fontWeight: 'bold', fontSize: 20, alignSelf: 'center'}}>
        Items expiring in next 3 days.
      </Text>
      <Content style={{marginTop: -10}}>
        {/* the entire outerpart */}
        <Body style={styles.listContainer}>
          {/* the header of table */}

          <View style={styles.tableHeader}>
            <CardItem
              style={{
                backgroundColor: 'rgba(255,255,255,0)',
                justifyContent: 'center',
              }}>
              <Text style={styles.productHeader}>Product</Text>
              <Text style={styles.itemsHeader}>Items</Text>
              <Text style={styles.daysHeader}>Days Left</Text>
            </CardItem>
          </View>

          {/* the inner list */}
{count>0?(  <ScrollView
            refreshControl={
              <RefreshControl refreshing={refreshing} onRefresh={onRefresh} />
            }>
            <View>
              <FlatList
                style={styles.flatlist}
                data={expiryList}
                // scrollEnabled={true}
                renderItem={({item}) => <ExpiryListItem item={item} />}
                
              />
            </View>
          </ScrollView>):(null)}
         
        </Body>
      </Content>
    </Container>
  );
}