티스토리 뷰
문제
현재 재생 중인 노래를 삭제할 경우 다음 index의 노래가 재생되어야 한다
현재 재생 중인 노래만 삭제할 경우 정상작동하나, 재생 중인 노래 + 다른 노래를 지우면 삭제한 노래가 재생되는 문제가 생겼다
해결 과정
체크박스로 선택 후 삭제 버튼을 누르면 필터로 현재 플리에 체크박스에 있는 데이터를 뺀 나머지를 수파베이스에 update 하는 방법으로 삭제를 만들었다
체크리스트가 재생 중인 노래 아이디랑 값이 같으면 변수에 담아주고 변수에 값이 있으면 현재 재생 중인 state 상태를 변경시켜주려 했는데
삭제 후 서버에 업데이트가 제대로 되지 않은 상태에서 다음 재생할 인덱스를 추적하려 해서 생긴 문제인 거 같다
삭제되고 남은 반환값에서 재생할 인덱스를 추적해야 하니까 서버에 업데이트 완료 후 작업해야지!!!!!!!!
그리고 객체는 자료구조가 자유로우니까 굳이 변수화시켜서 반환값을 넣지 않아도 된다
삭제되고 남은 반환값에서 무조건 0번 인덱스로 옮기니까 전혀 문제없이 작동된다
바꾸기 전 ( filter와 map을 체이닝 하여 한 번에 처리. )
- currentPlayList를 필터링한 후 musicId만을 추출하여 currentMusicData를 생성(메서드 체이닝 이용)
- mutate 메서드를 호출할 때 musicId로만 구성된 currentMusicData 전달
- 만약 현재 재생 중인 음악이 삭제 목록에 포함되어 있다면, currentPlayList의 musicIndex 위치에 있는 음악을 재생하도록 설정
const onDeleteCurrentMusicHandler = async () => {
if (checkedList.length === 0) {
alert('삭제할 노래를 선택해주세요')
return
}
if (window.confirm('선택 항목을 삭제하시겠습니까?')) {
const currentMusicData = currentPlayList
.filter((music) => !checkedList.includes(music.musicId))
.map((music) => music.musicId)
deleteMutation.mutate({ uid, currentMusicData })
setCheckedList([])
const isCurrentMusicDeleted = checkedList.includes(
currentPlaying!.musicId,
)
if (isCurrentMusicDeleted) {
// setMusicIndex((prev) => prev - checkedList.length)
console.log('musicIndex', musicIndex)
setCurrentPlaying(
currentPlayList[0]
? (currentPlayList[musicIndex] as CurrentPlayListType)
: null,
)
}
}
}
바꾼 후 ( filter로 걸러낸 후 map으로 musicId만 추출. )
- currentPlayList에서 checkedList에 포함되지 않은 음악을 필터링하여 currentMusicData 생성
- mutate 메서드를 호출할 때 currentMusicData의 musicId만 전달
- 만약 현재 재생 중인 음악이 삭제 목록에 포함되어 있다면, currentMusicData의 첫 번째 음악을 재생하도록 설정.
const onDeleteCurrentMusicHandler = async () => {
if (checkedList.length === 0) {
alert('삭제할 노래를 선택해주세요')
return
}
if (window.confirm('선택 항목을 삭제하시겠습니까?')) {
const currentMusicData = currentPlayList.filter(
(music) => !checkedList.includes(music.musicId),
)
deleteMutation.mutate({
uid,
currentMusicData: currentMusicData.map((music) => music.musicId),
})
setCheckedList([])
const isCurrentMusicDeleted = checkedList.includes(
currentPlaying!.musicId,
)
if (isCurrentMusicDeleted) {
setCurrentPlaying(currentMusicData[0] as CurrentPlayListType)
}
}
}
'TIL > 최종프로젝트' 카테고리의 다른 글
[최종프로젝트] 플레이 리스트 인덱스 변경 드래그앤 드롭 (세션 저장안됨) (0) | 2024.04.26 |
---|---|
[최종프로젝트] 드래그 앤 드롭 플레이리스트 추가 (dataTransfer.setData) (0) | 2024.04.23 |
[최종프로젝트] 테일윈드 (tailwind CSS) (0) | 2024.04.16 |
[최종프로젝트] 현재 재생 상태 유지 (State) (0) | 2024.04.15 |
[최종프로젝트] 두개의 배열 중복되지않는 값 찾기 (Set , every ) (0) | 2024.04.10 |