Skip to content Skip to sidebar Skip to footer

Store Not Updated In Redux?

In the 'Favorite List' reducer I have two helper function 'Add/Remove' item from the array the Add work well but Remove it does not update the store in the actual time, because I h

Solution 1:

Thanks for the live demo, it helped a lot to see the whole picture. The issue is that your view is not actually using the values in your Redux store at all. The reducer is fine and everything is working behind the scenes, but take a look...

const mapStateToProps = state => {
  return {
    favorite: state,
  };
};

This is your mapStateToProps method, and favorite contains an array of the favorite tracks that is successfully being updated whenever you dispatch an action. The reason why your view is not updated accordingly is that you're not using this array anywhere.

<Icon
  style={{color:"#00f"}}
  type="MaterialIcons"
  name={this.state.isFavorite ? 'favorite' : 'favorite-border'}
/>

In this piece of code, what you're checking is the value of a isFavorite property inside of your component's inner state. The reason why it works when you add a favorite is because you're calling setState at the beginning of addToFavorite. On the contrary, deleteFromFavorite is missing that setState call, which is the reason your icon is not changing.

If you want to use what you have in the Redux store to determine which icon to show, you should change your code so it uses this.props.favorite, which is the property that actually references the store and changes according to your actions.

constisCurrentTrackFavorite = () => {
  const { tunes, currentTrackIndex } = this.state;
  const currentTrackId = tunes[currentTrackIndex].track_id;

  // Check array in the Redux store to see if the track has been added to favoritesreturnthis.props.favorite.findIndex(track => track.track_id === currentTrackId) != -1;
};

render() {
  <Iconstyle={{color:"#00f"}}
    type="MaterialIcons"name={isCurrentTrackFavorite() ? 'favorite' : 'favorite-border'}
  />
}

By making this change, your component will be really listening to the contents of the store and should update the view whenever the array of favorites changes.

Post a Comment for "Store Not Updated In Redux?"