Search code examples
javascriptreactjsreact-nativereact-native-videoytdl

How can I get the link to be loaded before the component is rendered?


I'm using react-native-ytdl and react-native-video

I get youtube play link from "react-native-ytdl" and I play from "react-native-video"

but "react-native-ytdl' is using async When the component is loaded, the first testvalue comes out as undefined, enter image description here

and when the async is complete, the link is re-rendered. enter image description here

ytdl code

componentDidMount(){
            
            const {route, navigation} = this.props; 
            const {gameVid} = route.params;
            
            
                const rendertest = async (gameVid) => {

        
                    const format = await ytdl(gameVid, { quality: '22'});
                    let test = JSON.stringify(format[0].url);
                        
                    return test
                    
                }
            
             
                    rendertest(gameVid).then(finalValue => {
                        console.log(typeof(finalValue)+": "+finalValue)
                        //this.state.testvalue = finalValue;
                        this.setState({
                            testvalue: finalValue,
                            
                        });
                       
                        
                    })
    
            
            
            
        }

react-native-video code

<Video source={{uri: this.state.testvalue}}
                            
                            
                            resizeMode = "cover"
                            isNetwork = {this.state.done}

                            style={{width: '100%', height: 250,
                                position:'absolute',
                                
                            }}
                            
        
        
                    />

It seems that the video does not play normally because it is initially undefined

How can I get the link to be loaded before the component is rendered..?


Solution

  • You can conditionally render the Video component. That way, the Video component will render if this.state.testvalue is truthy

    {this.state.testvalue ? (
        <Video
            source={{uri: this.state.testvalue}}
            resizeMode="cover"
            isNetwork={this.state.done}
            style={{width: '100%', height: 250, position:'absolute'}}
        />
    ) : null}