| 1 | import {
|
|---|
| 2 | createContext,
|
|---|
| 3 | useContext,
|
|---|
| 4 | useEffect,
|
|---|
| 5 | useState,
|
|---|
| 6 | type Dispatch,
|
|---|
| 7 | type ReactNode,
|
|---|
| 8 | type SetStateAction,
|
|---|
| 9 | } from "react";
|
|---|
| 10 | import type { BasicPlaylist } from "../utils/types";
|
|---|
| 11 | import axiosInstance from "../api/axiosInstance";
|
|---|
| 12 | import { toast } from "react-toastify";
|
|---|
| 13 | import { getErrorMessage } from "../utils/error";
|
|---|
| 14 | import { useAuth } from "./authContext";
|
|---|
| 15 | interface PlaylistContextType {
|
|---|
| 16 | createdPlaylists: BasicPlaylist[] | undefined;
|
|---|
| 17 | setCreatedPlaylists: Dispatch<SetStateAction<BasicPlaylist[] | undefined>>;
|
|---|
| 18 | isLoading: boolean;
|
|---|
| 19 | refreshPlaylists: (addedSong: boolean) => Promise<void>;
|
|---|
| 20 | }
|
|---|
| 21 |
|
|---|
| 22 | interface PlaylistProviderProps {
|
|---|
| 23 | children: ReactNode;
|
|---|
| 24 | }
|
|---|
| 25 |
|
|---|
| 26 | const PlaylistContext = createContext<PlaylistContextType>({
|
|---|
| 27 | createdPlaylists: undefined,
|
|---|
| 28 | setCreatedPlaylists: () => {},
|
|---|
| 29 | isLoading: false,
|
|---|
| 30 | refreshPlaylists: async (addedSong: boolean) => {},
|
|---|
| 31 | });
|
|---|
| 32 |
|
|---|
| 33 | const 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 |
|
|---|
| 76 | export const useCreatedPlaylists = () => useContext(PlaylistContext);
|
|---|
| 77 |
|
|---|
| 78 | export default PlaylistProvider;
|
|---|