aretherecookies-mobile/js/pages/List.js
2018-04-22 12:19:58 -05:00

96 lines
2.4 KiB
JavaScript

// @flow
import React, { Component } from 'react';
import Food from './Food';
import Places from './Places';
import ScrollableTabView from 'react-native-scrollable-tab-view';
import theme from '../ui-theme.js';
import { type RoutingContextFlowTypes, routingContextPropTypes } from '../routes';
import { getSearch } from '../helpers/RouteHelpers';
import { getCurrentPosition, getPositionFromZip } from '../apis/PositionApi';
const tabs = ['food', 'places'];
const getTabIndex = ({
match: {
params: { type = '' },
},
}: RoutingContextFlowTypes): number => {
return tabs.indexOf(type) || 0;
};
type TabView = {
goToPage: (page: number) => void,
state: {
currentPage: number,
},
};
class List extends Component {
static contextTypes = routingContextPropTypes;
props: RoutingContextFlowTypes;
context: RoutingContextFlowTypes;
tabView: TabView;
// TODO convert this component to SFC using recompose
// also, figure out a less lifecyle-y way to do this request
componentDidMount() {
const { positionBy = 'zip' } = getSearch(this.context);
if (positionBy === 'location') {
getCurrentPosition();
} else {
getPositionFromZip();
}
}
updateTabRoute = ({ i }: { i: number }) => {
const currentTab = getTabIndex(this.props);
if (currentTab !== i) {
/*
routing is slow in react-native so this setTimeout allows for the stateful
TabView component to re-render itself before we make a route change
(which we expect will then re-render with no tab change)
*/
setTimeout(() => {
this.context.router.history.replace(`/list/${tabs[i]}`);
});
}
};
componentWillReceiveProps(nextProps: RoutingContextFlowTypes) {
if (!this.tabView) {
return;
}
const currentTab = getTabIndex(this.props);
const nextTab = getTabIndex(nextProps);
if (currentTab !== nextTab) {
this.tabView.goToPage(nextTab);
}
}
setTabViewRef = (tabView: TabView) => (this.tabView = tabView);
render() {
return (
<ScrollableTabView
ref={this.setTabViewRef}
tabBarBackgroundColor={theme.topTabs.backgroundColor}
tabBarUnderlineStyle={theme.topTabs.selectedUnderlineStyle}
tabBarActiveTextColor={theme.topTabs.textColor}
tabBarInactiveTextColor={theme.topTabs.selectedTextColor}
prerenderingSiblingsNumber={Infinity}
onChangeTab={this.updateTabRoute}
initialPage={getTabIndex(this.props)}>
<Food tabLabel="FOOD" />
<Places tabLabel="PLACES" />
</ScrollableTabView>
);
}
}
export default List;