Skip to content Skip to sidebar Skip to footer

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

Solution 1:

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;

Post a Comment for "How To Check Item In Favorite List - Redux?"