source: frontend/src/context/playlistContext.tsx@ ce45c7a

main
Last change on this file since ce45c7a was ce45c7a, checked in by Dimitar Arsov <dimitararsov04@…>, 5 months ago

add song to playlist

  • Property mode set to 100644
File size: 2.0 KB
Line 
1import {
2 createContext,
3 useContext,
4 useEffect,
5 useState,
6 type Dispatch,
7 type ReactNode,
8 type SetStateAction,
9} from "react";
10import type { BasicPlaylist } from "../utils/types";
11import axiosInstance from "../api/axiosInstance";
12import { toast } from "react-toastify";
13import { getErrorMessage } from "../utils/error";
14import { useAuth } from "./authContext";
15interface PlaylistContextType {
16 createdPlaylists: BasicPlaylist[] | undefined;
17 setCreatedPlaylists: Dispatch<SetStateAction<BasicPlaylist[] | undefined>>;
18 isLoading: boolean;
19 refreshPlaylists: (addedSong: boolean) => Promise<void>;
20}
21
22interface PlaylistProviderProps {
23 children: ReactNode;
24}
25
26const PlaylistContext = createContext<PlaylistContextType>({
27 createdPlaylists: undefined,
28 setCreatedPlaylists: () => {},
29 isLoading: false,
30 refreshPlaylists: async (addedSong: boolean) => {},
31});
32
33const PlaylistProvider = ({ children }: PlaylistProviderProps) => {
34 const { user } = useAuth();
35 const [createdPlaylists, setCreatedPlaylists] = useState<
36 BasicPlaylist[] | undefined
37 >(undefined);
38 const [isLoading, setIsLoading] = useState(false);
39
40 const fetchCreatedPlaylists = async (addedSong: boolean) => {
41 if (!addedSong) {
42 setIsLoading(true);
43 }
44 try {
45 const data = await axiosInstance.get<BasicPlaylist[]>("/playlists/user");
46 setCreatedPlaylists(data.data);
47 } catch (error: any) {
48 toast.error(getErrorMessage(error));
49 } finally {
50 setIsLoading(false);
51 }
52 };
53
54 useEffect(() => {
55 if (user) {
56 fetchCreatedPlaylists(false);
57 } else {
58 setCreatedPlaylists(undefined);
59 }
60 }, [user]);
61
62 return (
63 <PlaylistContext.Provider
64 value={{
65 createdPlaylists,
66 setCreatedPlaylists,
67 isLoading,
68 refreshPlaylists: fetchCreatedPlaylists,
69 }}
70 >
71 {children}
72 </PlaylistContext.Provider>
73 );
74};
75
76export const useCreatedPlaylists = () => useContext(PlaylistContext);
77
78export default PlaylistProvider;
Note: See TracBrowser for help on using the repository browser.