I'm learning react-redux
, I have a very simple application which displays dummy songs from a static list, my current reducers look like the following:
import { combineReducers } from "redux";
var songs = [
{ title: "No Scrubs", duration: "4:05" },
{ title: "Song 2", duration: "3:55" },
{ title: "Song 3", duration: "2:23" },
{ title: "Song 4", duration: "1:75" },
];
const songsReducer = () => {
return songs;
};
const selectedSongReducer = (selectedSong = null, action) => {
if (action.type === "SONG_SELECTED") {
return action.payload;
}
return selectedSong;
};
const deleteSongReducer = (selectedSong = null, action) => {
console.log("delete called");
if (action.type === "SONG_DELETED") {
var newArray = songs.filter((item) => item !== action.payload);
console.log(newArray);
return newArray;
}
return selectedSong;
};
export default combineReducers({
songs: songsReducer,
selectedSong: selectedSongReducer,
deleteSong: deleteSongReducer,
});
the selectedSongReducer is working as expected, however, I'm trying to remove a song from the static list when calling deleteSongReducer I can see a new array in the console when logging it, yet the results are reflected within the UI and by that I mean the deleted song is not removed from the list. I'm not sure what I'm doing wrong, any pointers would be great.
CodePudding user response:
You're going at this with a non complete mindset about how the reducers should work. You need the delete action to be handled inside the songs reducer, not just some other reducer.
A reducer represents a part of the state of your application, such as songs, and handles all actions that should have an effect on that part. In simple terms, your songsReducer
should handle:
- initial state
- adding songs
- removing songs
- reordering songs
- any other action that could touch the array of songs
function songsReducer(state, action) {
switch (action.type) {
case 'SONG_DELETED':
return state.filter((item) => item !== action.payload);
case 'SONG_ADDED':
return ...;
default:
return state;
}
}
the selectedSong
can stay in another reducer, because it represents a different part of your state - not the list of songs but a pointer to which song is selected - and that is fine.
CodePudding user response:
can you check how many time your Console.log(song) in UI render ? after deleteSongReducer action performed , if its rendring two times then might be reducer resetting to its initialState.. although if you can share a codePen I can look deeper to it