feat: refactoring data fetching
This commit is contained in:
@@ -0,0 +1,54 @@
|
||||
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
|
||||
Reference in New Issue
Block a user