aretherecookies-mobile/js/enhancers/createFoodItemEnhancers.js

89 lines
2.2 KiB
JavaScript
Raw Normal View History

// @flow
import mapPropsStream from 'recompose/mapPropsStream';
import CreateFoodItem$, { emitter as emitCreateItemState } from '../streams/CreateFoodItemStream';
import { emitter as emitFoodItemsState } from '../streams/FoodItemsStream';
import { createFoodItem } from '../apis/FoodItemsApi';
import FoodItemRecord, { createFoodItem as buildFoodItem } from '../records/FoodItemRecord';
2018-11-24 10:43:26 -06:00
import Snackbar from 'react-native-snackbar';
export const withCreateFoodItemState = mapPropsStream(props$ => {
return props$.combineLatest(CreateFoodItem$, (props, state) => {
const { foodItem, loading, error } = state;
const setFoodItem = (foodItem: FoodItemRecord) => emitCreateItemState({ ...state, foodItem });
const setLoading = (loading: boolean) => emitCreateItemState({ ...state, loading });
const setError = (error: Error) => emitCreateItemState({ ...state, error });
const saveFoodItem = async () => {
2018-12-15 12:40:03 -06:00
try {
2018-03-04 09:02:21 -06:00
// insert new item into db and cast it into FoodItemRecord
const newItem = buildFoodItem(await createFoodItem(foodItem));
Snackbar.show({
title: foodItem.name + ' added',
backgroundColor: 'black',
color: 'white',
});
2018-11-24 10:43:26 -06:00
2018-03-04 09:02:21 -06:00
// notify food items state of new item
emitFoodItemsState(newItem);
// clear the create item form to default empty record
setFoodItem(new FoodItemRecord());
// allow caller to see what was created
return newItem;
2018-12-15 12:40:03 -06:00
} catch (err) {
const error = formatError(err);
Snackbar.show({
title: error,
duration: Snackbar.LENGTH_LONG,
backgroundColor: 'black',
color: 'white',
});
2018-12-15 12:40:03 -06:00
throw error;
}
};
return {
...props,
foodItem,
loading,
error,
setFoodItem,
saveFoodItem,
setLoading,
setError,
};
});
});
2018-12-15 12:40:03 -06:00
function getNameForKey(key) {
switch (key) {
case 'name':
return 'Name';
case 'placeId':
return 'Place';
case 'category':
return 'Category';
case 'quantity':
return 'Quantity';
case 'latitude':
case 'longitude':
default:
return '';
}
}
function formatError({ message } = {}) {
try {
const msgObj = JSON.parse(message);
if (msgObj.missingkeys) {
return `Please fill in ${msgObj.missingkeys.map(getNameForKey).join(', ')}`;
}
} catch (err) {} //eslint-disable-line
return message;
}