useAudioPlayer
useAudioPlayer copied to clipboard
Cannot read property 'player' of null
If you have an HTML element inside a react three fiber drei Html component, it won't "wait" for the audio player component to regiter or mount and I get this error.
Cannot read property 'player' of null
Even if I do...
const value = useAudioPlayer() const { ready } = value console.log(value) if (ready) { return ( <div className="player"> <3D react scene with HTML element /> </div> ) }
I have meet the same question. Are you find some way to fix that?
hi @carmandale thank you for opening this. Can you describe more about your issue? What library are you using this with? Perhaps we will need to collaborate on a fix if I am not familiar
@E-Kuerschner I am experiencing the same issue while attempting to load the example hook code in the README w/in storybook or Next.js app.
same here with nextjs. looks like its ssr related? I've created a simple codesandbox: https://codesandbox.io/s/react-use-audio-player-issue-71-o42ytf
I have the same problem on GatsbyJS and the solution was wrap the component inside the AudioPlayerProvider, hope this usefull 👍
The Provider has to be named in an upper component. The hook is called bevor the provider is returned, that's why the context (=player) is null.
Make a wrapper-component or use a component above. You can look at the example on this git repository. The author is using two different components. You don't need to provide a value for the Provider.
Tried this it doesn't work, this was only use I could find in examples
<AudioPlayerProvider>
<div>
<button onClick={togglePlayPause}>{playing ? 'Pause' : 'Play'}</button>
</div>
</AudioPlayerProvider>
And full code
import React from 'react';
import { useAudioPlayer, AudioPlayerProvider } from 'react-use-audio-player';
const AudioPlayer = ({ file }) => {
const { togglePlayPause, ready, loading, playing } = useAudioPlayer({
src: file,
format: 'mp3',
autoplay: false,
onend: () => console.log('sound has ended!'),
});
if (!ready && !loading) return <div>No audio to play</div>;
if (loading) return <div>Loading audio</div>;
return (
<AudioPlayerProvider>
<div>
<button onClick={togglePlayPause}>{playing ? 'Pause' : 'Play'}</button>
</div>
</AudioPlayerProvider>
);
};
export default AudioPlayer;
same error useAudioPlayer.ts:19 Uncaught TypeError: Cannot read properties of null (reading 'player') at useAudioPlayer (useAudioPlayer.ts:19:1)
Solved it by wrapping AudioPlayer in AudioPlayerProvider in imported file
<AudioPlayerProvider>
<AudioPlayer />
</AudioPlayerProvider>
@JanVeb's solution worked for me - make sure the AudioPlayer is wrapped inside AudioPlayerProvider (doesn't matter how far up your component tree this is - I've wrapped it at app level) - thanks :)
yep! the solution @JanVeb provided is the way the hook is designed to function. I can try and update the docs to make this more clear