55 lines
1.4 KiB
TypeScript
55 lines
1.4 KiB
TypeScript
import { createSlice, createAsyncThunk } from '@reduxjs/toolkit'
|
|
import type { Album } from '../../types'
|
|
import { getArtistAlbums } from '../../furumiApi'
|
|
|
|
export const fetchArtistAlbums = createAsyncThunk(
|
|
'albums/fetchByArtist',
|
|
async (artistSlug: string, { rejectWithValue }) => {
|
|
const data = await getArtistAlbums(artistSlug)
|
|
if (data === null) return rejectWithValue('Failed to fetch albums')
|
|
return { artistSlug, albums: data }
|
|
},
|
|
)
|
|
|
|
interface AlbumsState {
|
|
byArtist: Record<string, Album[]>
|
|
loading: boolean
|
|
error: string | null
|
|
}
|
|
|
|
const initialState: AlbumsState = {
|
|
byArtist: {},
|
|
loading: false,
|
|
error: null,
|
|
}
|
|
|
|
const albumsSlice = createSlice({
|
|
name: 'albums',
|
|
initialState,
|
|
reducers: {
|
|
clearAlbums(state) {
|
|
state.byArtist = {}
|
|
state.error = null
|
|
},
|
|
},
|
|
extraReducers: (builder) => {
|
|
builder
|
|
.addCase(fetchArtistAlbums.pending, (state) => {
|
|
state.loading = true
|
|
state.error = null
|
|
})
|
|
.addCase(fetchArtistAlbums.fulfilled, (state, action) => {
|
|
state.loading = false
|
|
state.byArtist[action.payload.artistSlug] = action.payload.albums
|
|
state.error = null
|
|
})
|
|
.addCase(fetchArtistAlbums.rejected, (state, action) => {
|
|
state.loading = false
|
|
state.error = action.payload as string ?? 'Unknown error'
|
|
})
|
|
},
|
|
})
|
|
|
|
export const { clearAlbums } = albumsSlice.actions
|
|
export default albumsSlice.reducer
|