I have a Flat List which renders items, each item has x amount of calories and On Press I want to add that to my calorie counter, however through Async Storage it works well until I go back to my home screen and click on a new item, it adds the new values to the end of the "string" rather to an Int.
For example when I render the list and click two items they add up perfectly and my calories display correctly, I then press home, go back to the tracker, search a new item and it adds it to the end e.g
totalCalories = 50
when I go back to tracking and add an item worth 30 calories this gets displayed
totalCalories = 5030 rather than 80
Here is my code:
export default class Tracker extends React.Component { static navigationOptions = { title: "Tracker", };constructor(props) { super(props); this.getData(); this.state = { isLoading: true, dataSource: null, show: false, totalCalories: 0, }; }
Fetching API method:
fetchData = (item) => { fetch( `https://api.edamam.com/api/food-database/parser?ingr=${item}&app_id=${APP_ID}&app_key=${APP_KEY}` ) .then((response) => response.json()) .then((responseJson) => { this.setState({ itemArray: responseJson.hints, }); }) .catch((error) => { console.log(error); }); Keyboard.dismiss(); };
The onPress function when an item is pressed, which also sets the data in Async Storage:
fetchOnPressOpacity = async (item) => { // console.log(this.state.totalCalories); this.state.totalCalories += item.food.nutrients.ENERC_KCAL; try { this.setState({}); await AsyncStorage.setItem("totalCalories", JSON.stringify(this.state.totalCalories) ); } catch (error) { console.log(error); } };
Async getData function:
getData = async () => { try { const totalCalories = await AsyncStorage.getItem("totalCalories"); // parseInt(totalCalories); if (totalCalories !== null) { this.setState({ totalCalories, }); } } catch (error) {} };
Render:
render() { const { navigate } = this.props.navigation; return (<View style={styles.container}><Button title="clear" onPress={() => this.resetCalories()} /><Text> Total Calories: {console.log(this.state.totalCalories)}{this.state.totalCalories}</Text><View style={styles.viewForInputContainer}><TextInput onChangeText={(text) => this.setState({ item: text })} style={styles.textInputContainer} clearTextOnFocus={true}><Text style={styles.textColour}> Search Food </Text></TextInput></View><Button title="Search" onPress={() => this.fetchData(this.state.item)} /><View style={styles.ViewFilterContainer}><TouchableOpacity style={styles.ViewFilterContainer}><View style={styles.filterButtonView}><Text style={styles.filterText}> Filter </Text></View></TouchableOpacity></View><View style={styles.paddingForResultsContainer}><FlatList style={styles.resultsBackground} data={this.state.itemArray} renderItem={({ item, index }) => (<TouchableOpacity onPress={() => this.fetchOnPressOpacity(item, index)}><View style={styles.resultsContainer}><View style={styles.textView}><Text style={styles.resultsText}> {item.food.label} {item.food.brand} {index}</Text></View><View style={styles.nutritionResultsText}><Text style={styles.resultsTextSubInfo}> F: {Math.round(item.food.nutrients.FAT)}</Text><Text style={styles.resultsTextSubInfo}> C: {Math.round(item.food.nutrients.CHOCDF)}</Text><Text style={styles.resultsTextSubInfo}> P: {Math.round(item.food.nutrients.PROCNT)}</Text><Text style={styles.resultsTextSubInfo}> K/Cal: {Math.round(item.food.nutrients.ENERC_KCAL)}</Text></View></View></TouchableOpacity> )} /></View><View style={styles.buttonContainer}><View><Button title="Tracker" onPress={() => navigate("Tracker")} color="white" /></View><Button title="Shops" onPress={() => navigate("Shops")} color="white" /><Button title="Home" onPress={() => navigate("Home")} color="white" /><Button title="Macros" onPress={() => navigate("Macros")} color="white" /></View></View> ); }