i have a question.
im creating a music platform(like spotify) with next js
and to manage states, i use redux toolkit
. to play a music, i added audio
in a component that has some components to change the music time or volume or etc. to change the volume or time or etc, i used useRef
hook and i change the music time almost like this(this is a component that return some elements for large devices only and if the device is small, audio style will be display: none;
):
//inside a component(for example AudioLarge.jsx)
const audioRef = useRef()
useEffect(() => {
//if ref is ready, change the time
if(audioRef.current) audioRef.current.currentTime = 50;
}, [])
return (
<>
<audio src={source} ref={audioRef} />
</>
)
the problem starts here. i want to access the ref from AudioLarge.jsx
in AudioSmall.jsx
component that returns some elements for small devices. i have a solution for this. i can store the music ref in redux state. but is it ok? is it a good solution for this? does it make problems in future? is there a better solution to access the music ref globally? thanks for helping :)
CodePudding user response:
Yes you can store it in redux store... you can store it in any state management system from context api to redux
but the best way is to declare reference to it in a reducer and means to updated its state right thru action right there in that reducer... i.e its own reducer to keep your code neat
//in your page
import { useRef } from 'react';
.......
const audioref = useRef(null);
<audio ref = {audioref} />
somewhere in your codes you store the reference in your store thru action
<button onClick = {() => addAudioRef(audioref)}>play</button>
in your reducer
switch(state.action) {
....
case 'audioref-added':
return {...state, audioref : payload.audioref.current.play()}
case 'audioref-stoped':
return {...state, audioref : state.audioref.current.stop()}
....
}