source: frontend/src/context/playlistContext.tsx@ 85512ff

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

save playlist

  • Property mode set to 100644
File size: 1.9 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: () => 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 () => {},
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 () => {
41 setIsLoading(true);
42 try {
43 const data = await axiosInstance.get<BasicPlaylist[]>("/playlists/user");
44 setCreatedPlaylists(data.data);
45 } catch (error: any) {
46 toast.error(getErrorMessage(error));
47 } finally {
48 setIsLoading(false);
49 }
50 };
51
52 useEffect(() => {
53 if (user) {
54 fetchCreatedPlaylists();
55 } else {
56 setCreatedPlaylists(undefined);
57 }
58 }, [user]);
59
60 return (
61 <PlaylistContext.Provider
62 value={{
63 createdPlaylists,
64 setCreatedPlaylists,
65 isLoading,
66 refreshPlaylists: fetchCreatedPlaylists,
67 }}
68 >
69 {children}
70 </PlaylistContext.Provider>
71 );
72};
73
74export const useCreatedPlaylists = () => useContext(PlaylistContext);
75
76export default PlaylistProvider;
Note: See TracBrowser for help on using the repository browser.