55 lines
1.5 KiB
TypeScript
55 lines
1.5 KiB
TypeScript
import { createSlice, createAsyncThunk } from '@reduxjs/toolkit'
|
|
import type { Track } from '../../types'
|
|
import { getArtistTracks } from '../../furumiApi'
|
|
|
|
export const fetchArtistTracks = createAsyncThunk(
|
|
'artistTracks/fetch',
|
|
async (artistSlug: string, { rejectWithValue }) => {
|
|
const data = await getArtistTracks(artistSlug)
|
|
if (data === null) return rejectWithValue('Failed to fetch artist tracks')
|
|
return { artistSlug, tracks: data }
|
|
},
|
|
)
|
|
|
|
interface ArtistTracksState {
|
|
byArtist: Record<string, Track[]>
|
|
loading: boolean
|
|
error: string | null
|
|
}
|
|
|
|
const initialState: ArtistTracksState = {
|
|
byArtist: {},
|
|
loading: false,
|
|
error: null,
|
|
}
|
|
|
|
const artistTracksSlice = createSlice({
|
|
name: 'artistTracks',
|
|
initialState,
|
|
reducers: {
|
|
clearArtistTracks(state) {
|
|
state.byArtist = {}
|
|
state.error = null
|
|
},
|
|
},
|
|
extraReducers: (builder) => {
|
|
builder
|
|
.addCase(fetchArtistTracks.pending, (state) => {
|
|
state.loading = true
|
|
state.error = null
|
|
})
|
|
.addCase(fetchArtistTracks.fulfilled, (state, action) => {
|
|
state.loading = false
|
|
state.byArtist[action.payload.artistSlug] = action.payload.tracks
|
|
state.error = null
|
|
})
|
|
.addCase(fetchArtistTracks.rejected, (state, action) => {
|
|
state.loading = false
|
|
state.error = action.payload as string ?? 'Unknown error'
|
|
})
|
|
},
|
|
})
|
|
|
|
export const { clearArtistTracks } = artistTracksSlice.actions
|
|
export default artistTracksSlice.reducer
|