Reputation: 61
I'm using Expo's Video component on my application and it uses ref methods to handle the video's state.
I need other components to be able to call methods such as .playAsync()
and .pauseAsync()
without passing them down as props.
Is is possible to call those methods by dispatching a redux action?
Upvotes: 3
Views: 2109
Reputation: 5929
I don't use ref a lot cause, I don't really like it and the docs of reactjs show why this is not the best way. I REALLY recommend you to read this first https://reactjs.org/docs/refs-and-the-dom.html. But sometime you have no choice so. If you really want to use it. You can do this like that :) Hope this is a good example for you :)
// VideoService.js
let _video;
function setVideo(videoRef) {
_video = videoRef
};
function play() {
return _video.playAsync();
}
function pause() {
return _video.pauseAsync()
}
export const VideoService = {
setVideo,
play,
pause
}
// YouCp.js
import { VideoService } from './VideoService';
class YourCp extends Component {
state = { }
render() {
return (
<Video ref={r => VideoService.setVideo(r)} />
);
}
}
export default YourCp;
// actions.js
import { VideoService } from './VideoService';
export const play = () => async dispatch => {
await VideoService.play()
// other logic
}
Upvotes: 1
Reputation: 1867
So, I'm unsure your exact use case but I'm fairly certain it's not good practice to pass refernces down like this in react. You really should just pass down an updateThisComp function to where-ever you need to manipulate the video.
https://reactjs.org/docs/refs-and-the-dom.html
You should add a method or action that updates the component statewhere the video lives by passing those .playAsync, etc...
It could look like this.
const updateVideoState = (actionType) => {
actionType === 'pause' ? 'updateYourReduxStoreVideoState' : undefined
// change updateYourReduxStoreVideoState === true || false
}
Then in your video component...
<SomeVideoPackage pause={this.props.reduxStoreVideoStatePause} />
// this.props.reduxStoreVideoStatePause === true || false
or....
componentDidMount(){
this.props.reduxStoreVideoStatePause ? this.referenceName.pauseAsync()
}
Upvotes: 0