티스토리 뷰

인덱스 드래그 앤 드롭은 되는데 DB가 배열 형태라 변경된 순서를 저장할 수 없으니 임시로 쥬스탄드를 이용해 세션에 순서 변경된 플리를 저장하려고 한다

개발자도구를 보면 세션에는 저장되나, 새로고침시 원래 순서로 바뀐다 대체 왜?

 

  const currentMusic = useCurrentMusicStore((state) => state.currentMusic)

  const [isDrag, setIsDrag] = useState(false)
  const [draggedItem, setDraggedItem] = useState<MusicInfoType | null>(null)
  const [dragIndex, setDragIndex] = useState<number>(-1)
  const [customList, setCustomList] = useState<CurrentPlayListType[]>([])

//  const { setCustomList, customList } = useCurrentMusicStore()

  const { state } = JSON.parse(
    sessionStorage.getItem('currentMusicStore') as string,
  )
  const { currentPlayList } = state.currentMusicData
  // 인덱스 드래그 핸들러
  const indexDragHandler = (item: MusicInfoType, index: number) => {
    // 드래그 요소를 잡으면 요소의 정보와 인덱스를 스테이트에 저장
    setDraggedItem(item)
    setDragIndex(index)
  }

  const indexChangeDropHandler = (
    dropIndex: number, // 드롭 위치의 인덱스
  ) => {
    // 드래그 요소가 없거나, 현재 리스트가 없으면 반환
    if (!draggedItem || !currentPlayList) {
      return
    }

    // 드래그된 요소의 인덱스와 드롭할 인덱스가 동일하지 않으면 실행(기존 인덱스와 동일하면 이동시킬 필요없음)
    if (dragIndex !== dropIndex) {
      // 플리를 새 배열에 담음
      // const newPlayList = [...currentPlayList]

      // 드래그된 플리에서 드래드된 인덱스를 삭제
      const [draggedMusic] = currentPlayList.splice(dragIndex, 1)

      // 드롭한 순간 그 위치에 요소를 삽입
      currentPlayList.splice(dropIndex, 0, draggedMusic)

	  // 변경된 플레이리스트로 화면을 다시 렌더링
      setCustomList(newPlayList as CurrentPlayListType[])


      // 세션스토리지에 저장
      currentMusic(currentPlayList)
   
      // console.log('customList', customList)
      //세션 스토리지에 변경사항이 저장되지않음
    }

    // 드래그 요소와 인덱스 초기화
    setDraggedItem(null)
    setDragIndex(-1)
  }

 


Store 브라우저 세션 저장

type CurrentMusicStore = {
  currentMusicData: {
    currentPlayList: CurrentPlayListType[]
  }
  currentMusic: (currentPlayList: CurrentPlayListType[]) => void
}

const currentMusicState = {
  currentMusicData: {
    currentPlayList: [],
  },
}

export const useCurrentMusicStore = create(
  persist<CurrentMusicStore>(
    (set, _) => ({
      ...currentMusicState,
      currentMusic: (currentPlayList: CurrentPlayListType[]) => {
        set({ currentMusicData: { currentPlayList } })
      },
    }),
    {
      name: 'currentMusicStore',
      storage: createJSONStorage(() => sessionStorage),
    },
  ),
)
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
TAG
more
«   2024/09   »
1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30
글 보관함