Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
119 views
in Technique[技术] by (71.8m points)

javascript - How to check item in favorite list - redux?

I have two functions,

1- Add Song to favorite List: I send an request to endpoint that's add a song to user favorite list, its add song based on song_id I passed in body request.

2- Remove Song from the favorite list: as previous but remove song from a favorite list based on song_id.

So in Player Component, I have a heart Icon that's called functions it's when users click on it i call to add a song, else i call to remove the song.

All these stuff work without redux!

So I want to save song_id and bassed on it i want to add a checker if this song_id exist that's mean this song is in a favorite list before "heart icon will be is fulled" when user click on it I want to remove this song from favorite list So I call the second function To send a request to server and so on.

So i make an action/reducer for this case but i think it's not well.

UI "Player Component" - "without redux"

  addToFavorite = async () => {
    const {tunes, token, currentTrackIndex} = this.state;
    this.setState({isFavorite: true});
    let id = tunes[currentTrackIndex].id;
    try {
      let AuthStr = `Bearer ${token}`;
      const headers = {
        'Content-Type': 'application/json',
        Authorization: AuthStr,
      };
      let response = await API.post(
        '/btn_add_favourite',
        {
          id,
        },
        {
          headers: headers,
        },
      );
      if (response.data.status === 'success') {
        alert('added');
      } else {
        alert('already exist');
      }
    } catch (err) {
      this.setState({isFavorite: false});
      console.log(err);
    }
  };

  deleteFromFavorite = async () => {
    const {tunes, token, isFavorite, currentTrackIndex} = this.state;

    let id = tunes[currentTrackIndex].id;
    console.log(tunes[currentTrackIndex]);
    try {
      let AuthStr = `Bearer ${token}`;
      const headers = {
        'Content-Type': 'application/json',
        Authorization: AuthStr,
      };
      if (isFavorite) {
        let response = await API.post(
          '/favourite_delete',
          {
            tracks_id: id,
          },
          {
            headers: headers,
          },
        );
        if (response.status === 200) {
          alert('song deleted from your favorite list');
          this.setState({isFavorite: false});
        }
        console.log(response);
      }
    } catch (err) {
      console.log(err);
    }
  };



   <Button
              onPress={() =>
                this.state.isFavorite // Not using redux yet so by default false
                  ? this.deleteFromFavorite()
                  : this.addToFavorite()
              }
              transparent
              style={styles.btnTransparent}>
              <Icon
                style={styles.iconColor}
                type="MaterialIcons"
                name={this.state.isFavorite ? 'favorite' : 'favorite-border'}
              />
            </Button>

Redux Stuff

Action/isFavoriteAction.js

import {ADD_TO_FAVORITE, REMOVE_FROM_FAVORITE} from './types';

export const addToFavoriteFunction = isFavorite => {
  return {
    type: ADD_TO_FAVORITE,
    payload: isFavorite,
  };
};

export const removeFromFavoriteFunction = isFavorite => {
  return {
    type: REMOVE_FROM_FAVORITE,
    payload: isFavorite,
  };
};

reducer/isFavorite.js

import {ADD_TO_FAVORITE, REMOVE_FROM_FAVORITE} from '../actions/types';

let initial_state = {
  isFavorite: false,
};

const isFavoriteReducer = (state = initial_state, action) => {
  switch (action.type) {
    case ADD_TO_FAVORITE:
      state = {
        ...state,
        isFavorite: true,
      };
      break;
    case REMOVE_FROM_FAVORITE:
      state = {
        ...state,
        isFavorite: false,
      };
      break;
    default:
      return state;
  }
  return state;
};

export default isFavoriteReducer;
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Specifically for the reducer part, I see you are creating a state for a single song, I would recommend you to have the full list of songs in Redux, then you can handle it this way:

import { ADD_TO_FAVORITE, REMOVE_FROM_FAVORITE } from "../actions/types";

let initialState = [];

/**
 *
 * @param {Array<Object>} songs A list of songs, this should be your state
 * @param {boolean} flag The boolean value, to fav or unfav a song
 * @return A new list of songs, with the updated isFavorite field for the song
 */
const updateSongFavoriteFlag = (songs, songId, flag) =>
    songs.map(song => {
        if (song.id === songId) {
            return { ...song, isFavorite: flag };
        }
        return song;
    });

const isFavoriteReducer = (state = initialState, action = {}) => {
    const { payload, type } = action;
    switch (action.type) {
        case ADD_TO_FAVORITE: {
            // Returning a new state instead of just altering the selected item
            // Where payload is the id of the song you want to mark as favorite
            return updateSongFavoriteFlag(state, payload, true);
        }
        case REMOVE_FROM_FAVORITE:
            return updateSongFavoriteFlag(state, payload, false);
        default:
            return state;
    }
    return state;
};

export default isFavoriteReducer;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...