Maintaining Functional Harmony: Ensuring Authentication Doesn’t Disrupt Player Component in React Application

//App.js:

`

import Sidebar from “./components/Sidebar”;

import Player from “./components/Player”;

import Display from “./components/Display”;

import { PlayerContext } from “./components/Playercontext”;

import { AuthContext } from “./components/AuthContext”;

import Login from “./components/Login”;

const App = () => {

const { audioRef, track } = useContext(PlayerContext);

const { isAuthenticated } = useContext(AuthContext);

if (!isAuthenticated) {

return ;

}

return (

);

};“
type here

//index.js:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>``
import ReactDOM from "react-dom/client";
import "./index.css";
import App from "./App";
import reportWebVitals from "./reportWebVitals";
import { BrowserRouter } from "react-router-dom";
import PlayerContextProvider from "./components/Playercontext";
import AuthProvider from "./components/AuthContext";
const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(
<React.StrictMode>
<BrowserRouter>
<AuthProvider>
<PlayerContextProvider>
<App />
</PlayerContextProvider>
</AuthProvider>
</BrowserRouter>
</React.StrictMode>
);
`
type here
Playercontext.js:
``
import { songsData } from "../assets/assets";
export const PlayerContext = createContext();
const PlayerContextProvider = (props) => {
const audioRef = useRef();
const seekBg = useRef();
const seekBar = useRef();
const [track, setTrack] = useState(songsData[2]);
const [playStatus, setPlayStatus] = useState(false);
const [time, setTime] = useState({
currentTime: {
second: 0,
minute: 0,
},
totalTime: {
second: 0,
minute: 0,
},
});
const [favorites, setFavorites] = useState([]);
const play = () => {
if (audioRef.current) {
audioRef.current.play();
setPlayStatus(true);
}
};
const pause = () => {
if (audioRef.current) {
audioRef.current.pause();
setPlayStatus(false);
}
};
const playwithId = async (id) => {
await setTrack(songsData[id]);
if (audioRef.current) {
await audioRef.current.play();
setPlayStatus(true);
}
};
const previous = async () => {
if (track.id > 0) {
await setTrack(songsData[track.id - 1]);
if (audioRef.current) {
await audioRef.current.play();
setPlayStatus(true);
}
}
};
const next = async () => {
if (track.id < songsData.length - 1) {
await setTrack(songsData[track.id + 1]);
if (audioRef.current) {
await audioRef.current.play();
setPlayStatus(true);
}
}
};
const seekSong = async (e) => {
if (audioRef.current) {
audioRef.current.currentTime =
(e.nativeEvent.offsetX / seekBg.current.offsetWidth) *
audioRef.current.duration;
}
};
const addToFavorites = (song) => {
setFavorites((prevFavorites) => {
const isAlreadyFavorite = prevFavorites.some(
(fav) => fav.name === song.name
);
if (!isAlreadyFavorite) {
return [...prevFavorites, song];
}
return prevFavorites;
});
};
const removeFromFavorites = (song) => {
setFavorites((prevFavorites) => {
return prevFavorites.filter((fav) => fav.name !== song.name);
});
};
const contextValue = {
audioRef,
seekBg,
seekBar,
track,
setTrack,
playStatus,
setPlayStatus,
time,
setTime,
play,
pause,
playwithId,
previous,
next,
seekSong,
favorites,
addToFavorites,
removeFromFavorites,
};
useEffect(() => {
const updateSeekBar = () => {
if (audioRef.current) {
const currentTime = audioRef.current.currentTime;
const duration = audioRef.current.duration;
if (duration) {
seekBar.current.style.width = (currentTime / duration) * 100 + "%";
}
setTime({
currentTime: {
second: Math.floor(currentTime % 60),
minute: Math.floor(currentTime / 60),
},
totalTime: {
second: Math.floor(duration % 60),
minute: Math.floor(duration / 60),
},
});
}
};
if (audioRef.current) {
audioRef.current.ontimeupdate = updateSeekBar;
}
return () => {
if (audioRef.current) {
audioRef.current.ontimeupdate = null;
}
};
}, [audioRef]);
return (
<PlayerContext.Provider value={contextValue}>
{props.children}
</PlayerContext.Provider>
);
};
export default PlayerContextProvider;
//player.js:`
type here
``
import { assets } from "../assets/assets";
import { PlayerContext } from "./Playercontext";
const Player = () => {
const {
seekBar,
seekBg,
playStatus,
play,
pause,
track,
time,
previous,
next,
seekSong,
} = useContext(PlayerContext);
return (
<div className="h-[10%] px-4 bg-black flex justify-between items-center text-white">
<div className="hidden lg:flex items:center gap-4">
<img className="w-12" src={track.image} alt="song1" />
<div>
<p>{track.name}</p>
<p>{track.desc}</p>
</div>
</div>
<div className="flex flex-col items-center gap-1 m-auto">
<div className="flex gap-4">
<img
className="w-4 cursor-pointer"
src={assets.shuffle_icon}
alt="shuffle"
/>
<img
onClick={previous}
className="w-4 cursor-pointer"
src={assets.prev_icon}
alt="previous"
/>
{playStatus ? (
<img
onClick={pause}
className="w-4 cursor-pointer"
src={assets.pause_icon}
alt="play"
/>
) : (
<img
onClick={play}
className="w-4 cursor-pointer"
src={assets.play_icon}
alt="play"
/>
)}
<img
onClick={next}
className="w-4 cursor-pointer"
src={assets.next_icon}
alt="next"
/>
<img
className="w-4 cursor-pointer"
src={assets.loop_icon}
alt="loop"
/>
</div>
<div className="flex items-center gap-5">
<p>
{time.currentTime.minute}:{time.currentTime.second}
</p>
<div
onClick={seekSong}
ref={seekBg}
className="w-[60vw] max-w-[500px] bg-gray-400 rounded-full cursor-pointer"
>
<hr
ref={seekBar}
className="h-1 border-none w-0 bg-green-700 rounded-full"
></hr>
</div>
<p>
{time.totalTime.minute}:{time.totalTime.second}
</p>
</div>
</div>
<div className="hidden lg:flex items-center gap-2 opacity-75 mt-4">
<img className="w-4" src={assets.plays_icon} alt="plays" />
<img className="w-4" src={assets.mic_icon} alt="mic" />
<img className="w-4" src={assets.queue_icon} alt="queue" />
<img className="w-4" src={assets.speaker_icon} alt="speaker" />
<img className="w-4" src={assets.volume_icon} alt="volume" />
<div className="w-20 bg-slate-100 h-1 rounded"></div>
<img className="w-4" src={assets.mini_player_icon} alt="mini_player" />
<img className="w-4" src={assets.zoom_icon} alt="zoom" />
</div>
</div>
);
};
export default Player;
`
type here
</code>
<code>`` import ReactDOM from "react-dom/client"; import "./index.css"; import App from "./App"; import reportWebVitals from "./reportWebVitals"; import { BrowserRouter } from "react-router-dom"; import PlayerContextProvider from "./components/Playercontext"; import AuthProvider from "./components/AuthContext"; const root = ReactDOM.createRoot(document.getElementById("root")); root.render( <React.StrictMode> <BrowserRouter> <AuthProvider> <PlayerContextProvider> <App /> </PlayerContextProvider> </AuthProvider> </BrowserRouter> </React.StrictMode> ); ` type here Playercontext.js: `` import { songsData } from "../assets/assets"; export const PlayerContext = createContext(); const PlayerContextProvider = (props) => { const audioRef = useRef(); const seekBg = useRef(); const seekBar = useRef(); const [track, setTrack] = useState(songsData[2]); const [playStatus, setPlayStatus] = useState(false); const [time, setTime] = useState({ currentTime: { second: 0, minute: 0, }, totalTime: { second: 0, minute: 0, }, }); const [favorites, setFavorites] = useState([]); const play = () => { if (audioRef.current) { audioRef.current.play(); setPlayStatus(true); } }; const pause = () => { if (audioRef.current) { audioRef.current.pause(); setPlayStatus(false); } }; const playwithId = async (id) => { await setTrack(songsData[id]); if (audioRef.current) { await audioRef.current.play(); setPlayStatus(true); } }; const previous = async () => { if (track.id > 0) { await setTrack(songsData[track.id - 1]); if (audioRef.current) { await audioRef.current.play(); setPlayStatus(true); } } }; const next = async () => { if (track.id < songsData.length - 1) { await setTrack(songsData[track.id + 1]); if (audioRef.current) { await audioRef.current.play(); setPlayStatus(true); } } }; const seekSong = async (e) => { if (audioRef.current) { audioRef.current.currentTime = (e.nativeEvent.offsetX / seekBg.current.offsetWidth) * audioRef.current.duration; } }; const addToFavorites = (song) => { setFavorites((prevFavorites) => { const isAlreadyFavorite = prevFavorites.some( (fav) => fav.name === song.name ); if (!isAlreadyFavorite) { return [...prevFavorites, song]; } return prevFavorites; }); }; const removeFromFavorites = (song) => { setFavorites((prevFavorites) => { return prevFavorites.filter((fav) => fav.name !== song.name); }); }; const contextValue = { audioRef, seekBg, seekBar, track, setTrack, playStatus, setPlayStatus, time, setTime, play, pause, playwithId, previous, next, seekSong, favorites, addToFavorites, removeFromFavorites, }; useEffect(() => { const updateSeekBar = () => { if (audioRef.current) { const currentTime = audioRef.current.currentTime; const duration = audioRef.current.duration; if (duration) { seekBar.current.style.width = (currentTime / duration) * 100 + "%"; } setTime({ currentTime: { second: Math.floor(currentTime % 60), minute: Math.floor(currentTime / 60), }, totalTime: { second: Math.floor(duration % 60), minute: Math.floor(duration / 60), }, }); } }; if (audioRef.current) { audioRef.current.ontimeupdate = updateSeekBar; } return () => { if (audioRef.current) { audioRef.current.ontimeupdate = null; } }; }, [audioRef]); return ( <PlayerContext.Provider value={contextValue}> {props.children} </PlayerContext.Provider> ); }; export default PlayerContextProvider; //player.js:` type here `` import { assets } from "../assets/assets"; import { PlayerContext } from "./Playercontext"; const Player = () => { const { seekBar, seekBg, playStatus, play, pause, track, time, previous, next, seekSong, } = useContext(PlayerContext); return ( <div className="h-[10%] px-4 bg-black flex justify-between items-center text-white"> <div className="hidden lg:flex items:center gap-4"> <img className="w-12" src={track.image} alt="song1" /> <div> <p>{track.name}</p> <p>{track.desc}</p> </div> </div> <div className="flex flex-col items-center gap-1 m-auto"> <div className="flex gap-4"> <img className="w-4 cursor-pointer" src={assets.shuffle_icon} alt="shuffle" /> <img onClick={previous} className="w-4 cursor-pointer" src={assets.prev_icon} alt="previous" /> {playStatus ? ( <img onClick={pause} className="w-4 cursor-pointer" src={assets.pause_icon} alt="play" /> ) : ( <img onClick={play} className="w-4 cursor-pointer" src={assets.play_icon} alt="play" /> )} <img onClick={next} className="w-4 cursor-pointer" src={assets.next_icon} alt="next" /> <img className="w-4 cursor-pointer" src={assets.loop_icon} alt="loop" /> </div> <div className="flex items-center gap-5"> <p> {time.currentTime.minute}:{time.currentTime.second} </p> <div onClick={seekSong} ref={seekBg} className="w-[60vw] max-w-[500px] bg-gray-400 rounded-full cursor-pointer" > <hr ref={seekBar} className="h-1 border-none w-0 bg-green-700 rounded-full" ></hr> </div> <p> {time.totalTime.minute}:{time.totalTime.second} </p> </div> </div> <div className="hidden lg:flex items-center gap-2 opacity-75 mt-4"> <img className="w-4" src={assets.plays_icon} alt="plays" /> <img className="w-4" src={assets.mic_icon} alt="mic" /> <img className="w-4" src={assets.queue_icon} alt="queue" /> <img className="w-4" src={assets.speaker_icon} alt="speaker" /> <img className="w-4" src={assets.volume_icon} alt="volume" /> <div className="w-20 bg-slate-100 h-1 rounded"></div> <img className="w-4" src={assets.mini_player_icon} alt="mini_player" /> <img className="w-4" src={assets.zoom_icon} alt="zoom" /> </div> </div> ); }; export default Player; ` type here </code>
``

import ReactDOM from "react-dom/client";

import "./index.css";

import App from "./App";

import reportWebVitals from "./reportWebVitals";

import { BrowserRouter } from "react-router-dom";

import PlayerContextProvider from "./components/Playercontext";

import AuthProvider from "./components/AuthContext";

const root = ReactDOM.createRoot(document.getElementById("root"));

root.render(

<React.StrictMode>

<BrowserRouter>

<AuthProvider>

<PlayerContextProvider>

<App />

</PlayerContextProvider>

</AuthProvider>

</BrowserRouter>

</React.StrictMode>

);




`
type here
Playercontext.js:

``

import { songsData } from "../assets/assets";

export const PlayerContext = createContext();

const PlayerContextProvider = (props) => {

const audioRef = useRef();

const seekBg = useRef();

const seekBar = useRef();

const [track, setTrack] = useState(songsData[2]);

const [playStatus, setPlayStatus] = useState(false);

const [time, setTime] = useState({

currentTime: {

second: 0,

minute: 0,

    },

totalTime: {

second: 0,

minute: 0,

    },

  });

const [favorites, setFavorites] = useState([]);

const play = () => {

if (audioRef.current) {

audioRef.current.play();

setPlayStatus(true);

    }

  };

const pause = () => {

if (audioRef.current) {

audioRef.current.pause();

setPlayStatus(false);

    }

  };

const playwithId = async (id) => {

await setTrack(songsData[id]);

if (audioRef.current) {

await audioRef.current.play();

setPlayStatus(true);

    }

  };

const previous = async () => {

if (track.id > 0) {

await setTrack(songsData[track.id - 1]);

if (audioRef.current) {

await audioRef.current.play();

setPlayStatus(true);

      }

    }

  };

const next = async () => {

if (track.id < songsData.length - 1) {

await setTrack(songsData[track.id + 1]);

if (audioRef.current) {

await audioRef.current.play();

setPlayStatus(true);

      }

    }

  };

const seekSong = async (e) => {

if (audioRef.current) {

audioRef.current.currentTime =

        (e.nativeEvent.offsetX / seekBg.current.offsetWidth) *

audioRef.current.duration;

    }

  };

const addToFavorites = (song) => {

setFavorites((prevFavorites) => {

const isAlreadyFavorite = prevFavorites.some(

        (fav) => fav.name === song.name

      );

if (!isAlreadyFavorite) {

return [...prevFavorites, song];

      }

return prevFavorites;

    });

  };

const removeFromFavorites = (song) => {

setFavorites((prevFavorites) => {

return prevFavorites.filter((fav) => fav.name !== song.name);

    });

  };

const contextValue = {

audioRef,

seekBg,

seekBar,

track,

setTrack,

playStatus,

setPlayStatus,

time,

setTime,

play,

pause,

playwithId,

previous,

next,

seekSong,

favorites,

addToFavorites,

removeFromFavorites,

  };

useEffect(() => {

const updateSeekBar = () => {

if (audioRef.current) {

const currentTime = audioRef.current.currentTime;

const duration = audioRef.current.duration;

if (duration) {

seekBar.current.style.width = (currentTime / duration) * 100 + "%";

        }

setTime({

currentTime: {

second: Math.floor(currentTime % 60),

minute: Math.floor(currentTime / 60),

          },

totalTime: {

second: Math.floor(duration % 60),

minute: Math.floor(duration / 60),

          },

        });

      }

    };

if (audioRef.current) {

audioRef.current.ontimeupdate = updateSeekBar;

    }

return () => {

if (audioRef.current) {

audioRef.current.ontimeupdate = null;

      }

    };

  }, [audioRef]);

return (

<PlayerContext.Provider value={contextValue}>

{props.children}

</PlayerContext.Provider>

  );

};



export default PlayerContextProvider;


//player.js:`
type here

``

import { assets } from "../assets/assets";

import { PlayerContext } from "./Playercontext";

const Player = () => {

const {

seekBar,

seekBg,

playStatus,

play,

pause,

track,

time,

previous,

next,

seekSong,

  } = useContext(PlayerContext);

return (

<div className="h-[10%] px-4 bg-black flex justify-between items-center text-white">

<div className="hidden lg:flex items:center gap-4">

<img className="w-12" src={track.image} alt="song1" />

<div>

<p>{track.name}</p>

<p>{track.desc}</p>

</div>

</div>

<div className="flex flex-col items-center gap-1 m-auto">

<div className="flex gap-4">

<img

className="w-4 cursor-pointer"

src={assets.shuffle_icon}

alt="shuffle"

/>

<img

onClick={previous}

className="w-4 cursor-pointer"

src={assets.prev_icon}

alt="previous"

/>

{playStatus ? (

<img

onClick={pause}

className="w-4 cursor-pointer"

src={assets.pause_icon}

alt="play"

/>

          ) : (

<img

onClick={play}

className="w-4 cursor-pointer"

src={assets.play_icon}

alt="play"

/>

          )}

<img

onClick={next}

className="w-4 cursor-pointer"

src={assets.next_icon}

alt="next"

/>

<img

className="w-4 cursor-pointer"

src={assets.loop_icon}

alt="loop"

/>

</div>

<div className="flex items-center gap-5">

<p>

{time.currentTime.minute}:{time.currentTime.second}

</p>

<div

onClick={seekSong}

ref={seekBg}

className="w-[60vw] max-w-[500px] bg-gray-400 rounded-full cursor-pointer"

>

<hr

ref={seekBar}

className="h-1 border-none w-0 bg-green-700 rounded-full"

></hr>

</div>

<p>

{time.totalTime.minute}:{time.totalTime.second}

</p>

</div>

</div>

<div className="hidden lg:flex items-center gap-2 opacity-75 mt-4">

<img className="w-4" src={assets.plays_icon} alt="plays" />

<img className="w-4" src={assets.mic_icon} alt="mic" />

<img className="w-4" src={assets.queue_icon} alt="queue" />

<img className="w-4" src={assets.speaker_icon} alt="speaker" />

<img className="w-4" src={assets.volume_icon} alt="volume" />

<div className="w-20 bg-slate-100 h-1 rounded"></div>

<img className="w-4" src={assets.mini_player_icon} alt="mini_player" />

<img className="w-4" src={assets.zoom_icon} alt="zoom" />

</div>

</div>

  );

};

export default Player;



`
type here
Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>
</code>
<code> </code>

I added an authentication feature to my React application using AuthProvider and AuthContext to manage user login. However, after implementing authentication, my Player component, which relies on PlayerContext for audio playback and state management, stopped working. The audio playback, time tracking, and seek bar functionality are no longer responsive. How can I ensure that authentication does not interfere with the functionality of my Player component, maintaining proper state management and context usage throughout my application?

New contributor

Siddhu Bora is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật