Skip to content

Instantly share code, notes, and snippets.

@voratham
Last active March 23, 2018 11:23
Show Gist options
  • Save voratham/21332eb7528cd7278c95bacfbc6200b1 to your computer and use it in GitHub Desktop.
Save voratham/21332eb7528cd7278c95bacfbc6200b1 to your computer and use it in GitHub Desktop.
RNInifinityLoadingFlatList + ExpressJs-Server-Side
import React, { Component } from "react";
import moment from 'moment';
import { Alert, Platform, StyleSheet, View, Dimensions, BackHandler, ToastAndroid, TouchableOpacity , FlatList , NativeModules, LayoutAnimation, } from "react-native";
import { Container, Grid, Row, Spinner, Col, Header, Title, Content, Footer, Input, Item, Button, Icon, Text, Thumbnail ,Card , CardItem , Left , Right , Body } from "native-base";
import {Loading} from "../CommonComponent";
import { Navigation, ScreenVisibilityListener } from "react-native-navigation";
import {observer} from 'mobx-react/native'
const DEFAULT_PADDING = { top: 300, right: 60, bottom: 300, left: 60 };
const { width, height } = Dimensions.get("window");
import * as store from "../../store";
const { UIManager } = NativeModules;
@observer
class TripList extends Component {
constructor(props) {
super(props);
this.bookStore = store.book;
this.list = null;
this.state = {
trips: [],
loading: true,
wl: width,
hl: 100,
temp_height_block: { h: null, status: true },
lock: true
};
this.props.navigator.setOnNavigatorEvent(
this.onNavigatorEvent.bind(this)
);
UIManager.setLayoutAnimationEnabledExperimental &&
UIManager.setLayoutAnimationEnabledExperimental(true);
}
onNavigatorEvent(event) {
if (event.type === "DeepLink") {
return this._handleDeepLink(event);
}
switch (event.id) {
case "willAppear":
break;
case "willDisappear":
break;
default:
break;
}
}
async componentDidMount() {
this.setState({ loading: false });
console.log("first loding");
console.log("-------------------------");
const res = await this.bookStore.getUserTrip();
if (res.length == 0) {
Alert.alert("Something wrong !!");
this.props.navigator.pop({});
} else {
this.setState({ trips: res.data });
}
}
_handlePushScreen(val) {
this.props.navigator.push({
screen: "TripDetails",
title: "Trip Details",
backButtonTitle: "",
passProps: { trip: val }
});
}
_handleLoadMore = async e => {
console.log("_handleLoadMore");
this.setState({ loading: true, wl: width, hl: 100 });
if (
this.bookStore.pageTrip.current >= this.bookStore.pageTrip.pageCount
) {
console.log("โหลดไม่ได้แล้ว");
return setTimeout(() => {
LayoutAnimation.spring();
this.setState({ loading: false, wl: 0, hl: 0, lock: true });
}, 3000);
} else {
console.log("โหลดต่อ");
console.log("lockloading scrollView double");
const res = await this.bookStore.getUserTrip();
if (res.status) {
this.setState({ trips: [...this.state.trips, ...res.data] });
LayoutAnimation.spring();
this.setState({ loading: false, wl: 0, hl: 0, lock: false });
}
}
};
_handleOnScroll(e) {
if (this.state.temp_height_block.status) {
this.setState({
temp_height_block: {
h:
e.nativeEvent.contentSize.height /
this.bookStore.tripLists.length,
status: false
}
});
}
let off_Y =
e.nativeEvent.contentOffset.y +
e.nativeEvent.layoutMeasurement.height;
let result = off_Y / this.state.temp_height_block.h;
if (result >= this.bookStore.tripLists.length && this.state.lock) {
this.setState({ lock: false }, () => {
this._handleLoadMore();
});
}
}
_renderListItem = ({ item: val }, index) => {
return (
<TouchableOpacity
style={{ flex: 1 }}
key={index}
onPress={() => this._handlePushScreen(val)}
>
<Card>
<CardItem>
<Left>
<View>
<View style={{ flexDirection: "row" }}>
<Icon
name="ios-clock-outline"
style={{ fontSize: 20 }}
/>
<Text style={{ fontWeight: "400" }}>
{moment(val.createDate).format(
"YYYY-DD-MM"
)}{" "}
{moment(val.createDate).format("LT")}
</Text>
</View>
<View
style={{
alignSelf: "flex-start",
paddingVertical: 5
}}
>
<Text note>
CARCODE : {val.driver.carCode}
</Text>
</View>
</View>
</Left>
<Right style={{ alignSelf: "flex-start" }}>
<Text style={{ fontWeight: "400" }}>
{val.fare} BATH
</Text>
<View style={{ paddingVertical: 5 }}>
{val.status === "complete" ? (
<Text
note
style={{
color: "red",
fontWeight: "bold"
}}
>
{"Not yet comment on trip"}
</Text>
) : null}
</View>
</Right>
</CardItem>
</Card>
</TouchableOpacity>
);
};
render() {
return (
<View style={{ flex: 1 }}>
<FlatList
onScroll={e => this._handleOnScroll(e)}
ref={c => (this.list = c)}
style={{ paddingHorizontal: 5, marginVertical: 10 }}
data={this.bookStore.tripLists}
keyExtractor={(item, index) => index}
renderItem={this._renderListItem}
refreshing={this.state.loading ? true : false}
ListFooterComponent={
this.state.loading && (
<Spinner
style={{
paddingVertical: 50,
width: this.state.wl,
height: this.state.hl,
backgroundColor: "transparent"
}}
color="#000"
/>
)
}
/>
</View>
);
}
}
export default TripList;
module.exports = async(app)=>{
app
.route('/promotion/news')
.get(async(req, res) => {
var
data, options,
input = req.query,
current = +input.page || 1
conditions = {status:true},
console.log(req.query)
console.log('current' ,current )
console.log('-------------------------')
page = {
current: current,
numRange: 4,
size: 5
};
options = {
limit: page.size, // 10
sort: {editDate: -1},
skip: (page.current - 1) * page.size // (1-1)*10 = 0 , (2-1)*10 =
};
data = await D._promotion.find(conditions, null, options);
page.rowCount = await D._promotion.count(conditions);
page.pageCount = Math.ceil(page.rowCount / page.size);
res.json({
status: true,
data,
page
});
})
};
import {observable, computed, action} from 'mobx';
import { mapStore , ui , user , socket } from './'
import _ from 'lodash'
import * as api from "./api";
import { user as UserStore } from './'
import {SERVER_API_URL} from '../config/'
const HEADER_FETCH_POST = { headers: { 'Accept': 'application/json', 'Content-Type': 'application/json' }, method: "POST" }
class Promotion {
@observable promotionList = [];
@observable page = { };
@action getPromotionList = async () => {
try {
this.page.current = this.page.current + 1;
console.log('[getPromotionList] :: ' , this.page.pageCount , this.page.current)
const res = await fetch(`${SERVER_API_URL}/promotion/news?page=${this.page.current}`);
const resJson = await res.json();
console.log('[getPromotionList] :' , resJson.page );
if(resJson.status){
this.promotionList = [ ...this.promotionList , ...resJson.data];
this.page = resJson.page;
console.log('[getPromotionList] :: ' , this.page)
return ({ status : true, data : resJson.data})
}else{
return ({ status : false})
}
} catch (error) {
console.log('[getPromotionList] error :: ' , error )
return ({ status : false})
}
}
}
export default new Promotion();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment