Search code examples
react-nativebookmarks

Add to favorites/ likes in React Native using AsyncStorage not working?


I have been working on add To Favorites functionality. Basically, I have two icon images, one with a heart of white background color, the other is a red-background heart. My Objects are houses . Each house can just be represented by a houseNumber, which is a string of characters consisting of digits and letters (alphanumerics) .

When the view loads for a specific house, I want to check if the current houseNumber is already saved in the favorites (asyncStorage). If it is then the red colored is displayed. If it is not part of the favorites, then the empty-colored heart is display

Here is my _updateList method, which is called upon the component mounts:

async _updateList() {
   const response = await AsyncStorage.getItem('listOflikes');
   const listOfLikes = await JSON.parse(response) || [];
   this.setState({
       favorites: listOfLikes
     });
   console.log(this.state.favorites);
   if (listOfLikes.includes(this.props.houseNumber)) {
     this.setState({ isLiked: true });
   }
   else {
     this.setState({ isLiked: false })
   }
   console.log(this.state.isLiked);
 }

On componentDidMount, the _updateList is called:

componentDidMount() {
    console.log(this.props.houseNumber);
    console.log(this.props.latitude);
    console.log(this.props.longitude);
    this._updateList();
 }

Now given that no house is yet added to favorites. When I click on the heart image, I am currently expecting the red heart to be displayed and the current house number to be added in asyncStorage. However, the favorites is still an empty array and the empty-colored hear image is displayed. Below are the rest of the functions:

async _addToFavorites() {
    const listOfHouses = [...this.state.favorites, this.props.houseNumber];

    await AsyncStorage.setItem('favorites',
    JSON.stringify(listOfHouses));
    this._updateList();
  }

 _onPressHeartButton() {
      if(this.state.isLiked){
    // remove from favorites
    }
   else{
    // add to favorites
    this._addToFavorites();
   }
  }

renderHeart() {
  if (this.state.isLiked) {
    return (
      <Image
        source={require('./images/ic_like_pressed.png')}
         style={{
           width: '50%',
           height: '50%',
           alignItems: 'flex-end',
           alignSelf: 'center',
           marginTop: 0,
           resizeMode: 'contain',
           marginBottom: 0,
           paddingBottom: 0,
           marginLeft: '20%'
         }}
      />
          );
  }
  else {
    return (
      <Image
        source={require('./images/ic_like_normal.png')}
         style={{
           width: '50%',
           height: '50%',
           alignItems: 'flex-end',
           alignSelf: 'center',
           marginTop: 0,
           resizeMode: 'contain',
           marginBottom: 0,
           paddingBottom: 0,
           marginLeft: '20%'
         }}
      />
    );
  }
}

The heart is displayed in the view like this:

<TouchableWithoutFeedback onPress={this._onPressHeartButton.bind(this)} >
   {this.renderHeart()}
</TouchableWithoutFeedback>

Solution

  • You are using two different keys for accessing the AsyncStorage instance("favorites" and "listOfLikes"). You must use the same key on both places.