-
-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathRecentSongs.context.tsx
More file actions
184 lines (154 loc) · 4.61 KB
/
RecentSongs.context.tsx
File metadata and controls
184 lines (154 loc) · 4.61 KB
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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
'use client';
import { useEffect } from 'react';
import { create } from 'zustand';
import type { PageDto, SongPreviewDtoType } from '@nbw/database';
import axiosInstance from '@web/lib/axios';
interface RecentSongsState {
recentSongs: (SongPreviewDtoType | null | undefined)[];
recentError: string;
isLoading: boolean;
hasMore: boolean;
selectedCategory: string;
categories: Record<string, number>;
page: number;
}
interface RecentSongsActions {
initialize: (initialRecentSongs: SongPreviewDtoType[]) => void;
setSelectedCategory: (category: string) => void;
increasePageRecent: () => Promise<void>;
fetchRecentSongs: () => Promise<void>;
fetchCategories: () => Promise<void>;
}
type RecentSongsStore = RecentSongsState & RecentSongsActions;
const adCount = 1;
const pageSize = 12;
const fetchCount = pageSize - adCount;
function injectAdSlots(
songs: SongPreviewDtoType[],
): Array<SongPreviewDtoType | undefined> {
const songsWithAds: Array<SongPreviewDtoType | undefined> = [...songs];
for (let i = 0; i < adCount; i++) {
const adPosition = Math.floor(Math.random() * (songsWithAds.length + 1));
songsWithAds.splice(adPosition, 0, undefined);
}
return songsWithAds;
}
export const useRecentSongsStore = create<RecentSongsStore>((set, get) => {
const fetchRecentSongs = async () => {
const { page, selectedCategory } = get();
set({ isLoading: true });
try {
const params: Record<string, any> = {
page,
limit: fetchCount, // TODO: fix constants
sort: 'recent',
order: 'desc',
};
if (selectedCategory) {
params.category = selectedCategory;
}
const response = await axiosInstance.get<PageDto<SongPreviewDtoType>>(
'/song',
{ params },
);
const fetchedSongs = response.data.content;
const newSongs = injectAdSlots(fetchedSongs);
set((state) => ({
recentSongs: [
...state.recentSongs.filter((song) => song !== null),
...newSongs,
],
hasMore: fetchedSongs.length >= fetchCount,
recentError: '',
}));
} catch (error) {
set((state) => ({
recentSongs: state.recentSongs.filter((song) => song !== null),
recentError: 'Error loading recent songs',
}));
} finally {
set({ isLoading: false });
}
};
return {
// Initial state
recentSongs: [],
recentError: '',
isLoading: false,
hasMore: true,
selectedCategory: '',
categories: {},
page: 1, // Start from page 1 since it's loaded server-side
// Actions
initialize: (initialRecentSongs) => {
set({
recentSongs: injectAdSlots(initialRecentSongs),
page: 1,
hasMore: true,
recentError: '',
});
},
fetchCategories: async () => {
try {
const response = await axiosInstance.get<Record<string, number>>(
'/song/categories',
);
set({ categories: response.data });
} catch (error) {
set({ categories: {} });
}
},
fetchRecentSongs: fetchRecentSongs,
setSelectedCategory: (category) => {
set({
selectedCategory: category,
page: 1, // Fetch from the first page when category changes
recentSongs: Array(pageSize).fill(null),
hasMore: true,
});
fetchRecentSongs();
},
increasePageRecent: async () => {
const { isLoading, recentError, hasMore, recentSongs } = get();
if (isLoading || recentError || !hasMore) {
return;
}
set({
recentSongs: [...recentSongs, ...Array(pageSize).fill(null)],
page: get().page + 1,
});
fetchRecentSongs();
},
};
});
// Hook to fetch categories on mount
export const useRecentSongsCategoriesLoader = () => {
const fetchCategories = useRecentSongsStore((state) => state.fetchCategories);
useEffect(() => {
fetchCategories();
}, [fetchCategories]);
};
// Legacy hook name for backward compatibility
export const useRecentSongsProvider = () => {
const store = useRecentSongsStore();
// Ensure recentSongs is always an array
return {
...store,
recentSongs: store.recentSongs || [],
};
};
// Provider component for initialization (now just a wrapper)
type RecentSongsProviderProps = {
children: React.ReactNode;
initialRecentSongs: SongPreviewDtoType[];
};
export function RecentSongsProvider({
children,
initialRecentSongs,
}: RecentSongsProviderProps) {
const initialize = useRecentSongsStore((state) => state.initialize);
useEffect(() => {
initialize(initialRecentSongs);
}, [initialRecentSongs, initialize]);
return <>{children}</>;
}