status.ts 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940
  1. import { AxiosInstance, AxiosResponse } from 'axios';
  2. import { useCallback, useContext, useEffect } from 'react';
  3. import { songInfoFetched } from '../actions';
  4. import { DispatchContext, StateContext } from '../context/state';
  5. import { Song } from '../types';
  6. import { getApiUrl } from '../utils/url';
  7. import { useRequestCallback } from './request';
  8. export function useCurrentlyPlayingSongInfo(): void {
  9. const state = useContext(StateContext);
  10. const dispatch = useContext(DispatchContext);
  11. const sendRequest = useCallback(
  12. (axios: AxiosInstance, id: number): Promise<AxiosResponse<Song>> =>
  13. axios.get(`${getApiUrl()}/song-info?id=${id}`),
  14. [],
  15. );
  16. const [onFetch, response, , cancelRequest] = useRequestCallback<number, Song>({ sendRequest });
  17. useEffect(() => {
  18. if (state.player.songId) {
  19. if (state.player.songId === state.songInfo?.id) {
  20. cancelRequest.current?.();
  21. } else {
  22. onFetch(state.player.songId);
  23. }
  24. } else if (state.songInfo?.id) {
  25. cancelRequest.current?.();
  26. dispatch(songInfoFetched(null));
  27. }
  28. }, [dispatch, state.player.songId, state.songInfo?.id, onFetch, cancelRequest]);
  29. useEffect(() => {
  30. if (response?.id === state.player.songId) {
  31. dispatch(songInfoFetched(response));
  32. }
  33. }, [dispatch, response, state.player.songId]);
  34. }