Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Reduxify #2

Open
wants to merge 9 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,9 @@ React Native based mobile app experimenting with map rendering in apps.
height="512"
/>

yarn storybook
yarn rn start

## Notes

- Uses the [Mapbox Maps API](https://www.mapbox.com/maps/) for rendering maps and geocoding.
Expand Down
5 changes: 4 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,10 @@
"react-native-config": "^0.11.7",
"react-native-snackbar": "^0.5.5",
"react-native-snap-carousel": "^3.7.5",
"react-native-vector-icons": "^6.4.2"
"react-native-vector-icons": "^6.4.2",
"react-redux": "^7.0.2",
"redux-logger": "^3.0.6",
"redux-starter-kit": "^0.4.3"
},
"devDependencies": {
"@storybook/addon-actions": "^4.1.16",
Expand Down
13 changes: 12 additions & 1 deletion src/App.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,19 @@
import React from 'react';
import { Provider } from 'react-redux';
import { configureStore, getDefaultMiddleware } from 'redux-starter-kit';
import logger from 'redux-logger';
import Home from './screens/Home';
import rootReducer from './state';

const store = configureStore({
reducer: rootReducer,
middleware: [...getDefaultMiddleware(), logger],
});

export default function App() {
return (
<Home />
<Provider store={store}>
<Home />
</Provider>
);
}
33 changes: 29 additions & 4 deletions src/components/LocationCard/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,11 @@ import PropTypes from 'prop-types';
import {
StyleSheet,
Text,
TouchableOpacity,
View,
ViewPropTypes,
} from 'react-native';
import Icon from 'react-native-vector-icons/Ionicons';

let styles;

Expand All @@ -14,12 +16,25 @@ export default function LocationCard(props) {
title,
address,
style,
showDelete,
onDelete,
} = props;
return (
<View style={[styles.container, style]}>
<Text style={styles.title} numberOfLines={2}>
{title}
</Text>
<View style={styles.row}>
<Text style={styles.title} numberOfLines={2}>
{title}
</Text>
{showDelete && (
<TouchableOpacity onPress={onDelete}>
<Icon
name="md-trash"
size={24}
style={styles.icon}
/>
</TouchableOpacity>
)}
</View>
<Text style={styles.subtext} numberOfLines={3}>
{address}
</Text>
Expand All @@ -31,11 +46,14 @@ LocationCard.propTypes = {
title: PropTypes.string.isRequired,
address: PropTypes.string.isRequired,
// onPress: PropTypes.function,
// onDelete: PropTypes.function,
showDelete: PropTypes.bool,
onDelete: PropTypes.func,
style: ViewPropTypes.style,
};
LocationCard.defaultProps = {
style: {},
showDelete: false,
onDelete: Function.prototype,
};

styles = StyleSheet.create({
Expand All @@ -48,12 +66,19 @@ styles = StyleSheet.create({
height: 120,
backgroundColor: 'rgba(255, 255, 255, 0.9)',
},
row: {
flexDirection: 'row',
},
title: {
flex: 1,
fontWeight: 'bold',
fontSize: 20,
},
subtext: {
fontSize: 16,
marginTop: 10,
},
icon: {
paddingHorizontal: 5,
},
});
72 changes: 72 additions & 0 deletions src/lib/request.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
import Config from 'react-native-config';

const HOST = Config.API_HOST;
const ACCESS_TOKEN = Config.API_ACCESS_TOKEN;

function createQueryParamString(params) {
function createQueryParam(name, value) {
const esc = encodeURIComponent;
return `${esc(name)}=${esc(value)}`;
}

/**
* Takes in params object and returns a flat list of
* query params, values to stringify. Handles array query params.
*/
function flattenParamList(paramsObj) {
return Object.entries(paramsObj).reduce(
(flatList, [param, value]) => {
if (Array.isArray(value)) {
return [
...flatList,
...value.map(val => [param, val]),
];
}

return [
...flatList,
[param, value],
];
},
[],
);
}

return flattenParamList(params)
.map(([name, value]) => createQueryParam(name, value))
.join('&');
}

function executeRequest(urlSuffix, method, params) {
const headers = {
Authorization: ACCESS_TOKEN,
'Content-Type': 'application/json',
'Cache-Control': 'no-cache',
};
const options = {
method,
headers,
};
let url = `http://${HOST}${urlSuffix}`;

if (method === 'GET') {
url += createQueryParamString(params);
} else {
options.body = JSON.stringify(params);
}

console.log(url);
return fetch(url, options);
}

export function get(urlSuffix, params = {}) {
return executeRequest(urlSuffix, 'GET', params);
}

export function post(urlSuffix, params = {}) {
return executeRequest(urlSuffix, 'POST', params);
}

export function del(urlSuffix) {
return executeRequest(urlSuffix, 'DELETE');
}
115 changes: 72 additions & 43 deletions src/screens/Home/index.js
Original file line number Diff line number Diff line change
@@ -1,53 +1,57 @@
import React, { Component } from 'react';
import {
Dimensions,
StyleSheet,
View,
} from 'react-native';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import Carousel from 'react-native-snap-carousel';
import Geocoder from '../../components/Geocoder';
import MapView from '../../components/MapView';
import LocationCard from '../../components/LocationCard';
import {
addMarker,
removeMarker,
getMarkedLocations,
} from '../../state';
import styles from './index.styles';

let styles;
const { width: vpWidth } = Dimensions.get('window');
const CAROUSEL_WIDTH = vpWidth;
const CAROUSEL_ITEM_WIDTH = vpWidth * 0.67;
const HELP_SLIDE = { id: 'HELP' };

export default class HomeScreen extends Component {
export class HomeScreen extends Component {
constructor(props) {
super(props);
this.state = {
center: null,
markers: [],
selectedLocationId: null,
// settleCarousel:
};
}

onLocationSelect = (locationObj) => {
const { dispatch } = this.props;

dispatch(addMarker(locationObj));
this.setState(
(state) => {
let newMarkers = state.markers;
if (!state.markers.map(m => m.id).includes(locationObj.id)) {
newMarkers = [...state.markers, locationObj];
}
return {
center: locationObj.center,
markers: newMarkers,
carouselIndex: newMarkers.length,
};
},
() => {
const { markers } = this.state;
{
// center: locationObj.center,
selectedLocationId: locationObj.id,
}, () => {
const { markers } = this.props;
const index = markers.findIndex(marker => marker.id === locationObj.id);
setTimeout(() => this.carousel.snapToItem(index + 1, true, false), 100);
setTimeout(() => this.carousel.snapToItem(index + 1, true, false), 300);
},
);
}

reset = () => {
this.setState({
center: null,
// center: null,
selectedLocationId: null,
});
this.carousel.snapToItem(0, true, false);
}
Expand All @@ -56,15 +60,20 @@ export default class HomeScreen extends Component {
if (slideIndex === 0) {
this.reset();
} else {
this.setState(
({ markers }) => ({
center: markers[slideIndex - 1].center,
}),
);
const { markers } = this.props;
this.setState({
// center: markers[slideIndex - 1].center,
selectedLocationId: markers[slideIndex - 1].id,
});
}
}

static renderLocationCard({ item }) {
deleteMarker(locationObj) {
const { dispatch } = this.props;
dispatch(removeMarker(locationObj.id));
}

renderLocationCard = ({ item }) => {
if (item.id === 'HELP') {
return (
<LocationCard
Expand All @@ -80,12 +89,37 @@ export default class HomeScreen extends Component {
style={styles.markersCarousel}
title={item.text}
address={item.place_name}
onDelete={() => this.deleteMarker(item)}
showDelete
/>
);
}

render() {
const { center, markers } = this.state;
const { selectedLocationId } = this.state;
const { markers } = this.props;
let center;
if (!selectedLocationId) {
center = null;
} else {
const indexInStore = markers.findIndex(location => location.id === selectedLocationId);
if (indexInStore > -1) {
// eslint-disable-next-line prefer-destructuring
center = markers[indexInStore].center;
} else {
console.log('BOOM');
}
}

// if (indexInStore > -1) {
// const selectedIndex = indexInStore + 1;
// center = markers[indexInStore].center;
// setTimeout(() => this.carousel.snapToItem(selectedIndex + 1, true, false), 50);
// } else {
// console.log('SKCSDLMCLSMCLDMLSD');
// center = null;
// }

return (
<View style={styles.container}>
<MapView
Expand All @@ -100,7 +134,7 @@ export default class HomeScreen extends Component {
<Carousel
ref={(c) => { this.carousel = c; }}
data={[HELP_SLIDE, ...markers]}
renderItem={this.constructor.renderLocationCard}
renderItem={this.renderLocationCard}
sliderWidth={CAROUSEL_WIDTH}
slideStyle={styles.slideStyle}
itemWidth={CAROUSEL_ITEM_WIDTH}
Expand All @@ -113,20 +147,15 @@ export default class HomeScreen extends Component {
}
}

styles = StyleSheet.create({
container: {
flex: 1,
},
searchBar: {
position: 'absolute',
top: 10,
},
markersCarousel: {
position: 'absolute',
bottom: 10,
},
slideStyle: {
minHeight: 140,
justifyContent: 'center',
},
});
HomeScreen.propTypes = {
dispatch: PropTypes.func.isRequired,
markers: PropTypes.arrayOf(PropTypes.object).isRequired,
};

function mapStateToProps(state) {
return {
markers: getMarkedLocations(state),
};
}

export default connect(mapStateToProps)(HomeScreen);
4 changes: 2 additions & 2 deletions src/screens/Home/index.stories.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import React from 'react';
import { storiesOf } from '@storybook/react-native';
import Home from './index';
import { HomeScreen } from './index';

storiesOf('Home', module).add('default', () => <Home />);
storiesOf('Home', module).add('default', () => <HomeScreen />);
Loading