react-native-video showing white Screen for 1 min then playing video

I am using this package to show video which I am getting fro pubnub message block , the require ment is once the video push from pubnub it will save locally
but video is playing first time push but after killing app and opening again it showing blank white screen for long time and then shows the video i tried to managed by states but unable to handle this issue

import React, { useEffect, useState,useRef } from 'react';
import { View, Text, StyleSheet, Dimensions, Image, ActivityIndicator, } from 'react-native';
import PubNub from 'pubnub';
import Video from 'react-native-video';
import AsyncStorage from '@react-native-async-storage/async-storage';
import RNFetchBlob from 'rn-fetch-blob';
import NetInfo from '@react-native-community/netinfo';

const HomeScreen = () => {
  const videoRef = useRef(null);
  const [mediaUrl, setMediaUrl] = useState('');
  const [displayID, setDisplayID] = useState('loading');
  const [mediaType, setMediaType] = useState('');
  const [progress, setProgress] = useState(0);
  const [loading, setLoading] = useState(false);

  const pubnub = new PubNub({
    // demokeys
    publishKey: 'pub-c-52eb18de-968d-4d2e-8e24-da7d49aac36d',
    subscribeKey: 'sub-c-863ea605-1972-4d02-be58-f9a4bce768fd',
    // productionKeys
    // publishKey: "pub-c-1edcf878-9b9d-4577-a260-21ec35fa5f09",
    // subscribeKey:"sub-c-59a0b640-b45b-4197-8cec-d20851980a5b",
    userId: displayID,
  });

  useEffect(() => {
    const loadDataAndSubscribe = async () => {
      let storedShortUuid = await AsyncStorage.getItem('shortUuid');
      let storedMediaUrl = await AsyncStorage.getItem('mediaUrl');
      let storedMediaType = await AsyncStorage.getItem('mediaType');
      if(storedMediaType && storedMediaUrl){
         setMediaUrl(storedMediaUrl);
        setMediaType(storedMediaType);
      }else{
        let downloadedMedia = await AsyncStorage.getItem("localMediaUrl")
        setMediaUrl(downloadedMedia)
      }
     
      if (!storedShortUuid) {
        storedShortUuid = Math.random().toString(36).substring(7);
        await AsyncStorage.setItem('shortUuid', storedShortUuid);
      }

      setDisplayID(storedShortUuid);
      subscribeToChannel(storedShortUuid);
     
    };

    loadDataAndSubscribe();
  }, []);

  const downloadMedia = async (mediaUrl, mediaType) => {
    setLoading(true);
    try {
      // Check if the device is online
      const netInfoState = await NetInfo.fetch();
      const isOnline = netInfoState.isConnected;
      
      // If the device is offline, attempt to load the media from local storage
      if (!isOnline) {
        const localMediaUrl = await AsyncStorage.getItem('localMediaUrl');
        if (localMediaUrl) {
          setLoading(false);
          setMediaUrl(localMediaUrl); // Set the media URL in state
          return localMediaUrl;
        }
      }
  
      const response = await RNFetchBlob.config({
        fileCache: true,
      }).fetch('GET', mediaUrl)
        .progress((received, total) => {
          const progress = (received / total) * 100;
          setProgress(progress);
        });
      
      const localPath = response.path();
      
      // Save the media to local storage for offline access
      await AsyncStorage.setItem('localMediaUrl', localPath);
  
      setLoading(false);
      setMediaUrl(localPath); // Set the media URL in state
      return localPath;
    } catch (error) {
      setLoading(false);
      console.error('Error downloading media:', error);
      return null;
    }
  };

  const handleMediaPlayback = async (message) => {
    const { mediaUrl, mediaType, downloadLocal } = message;
  
    if (downloadLocal) {
      // Download media locally if required
      const localPath = await downloadMedia(mediaUrl, mediaType);
  
      if (localPath) {
        setMediaUrl(localPath);
        setMediaType(mediaType);
      } else {
        console.error('Media download failed');
      }
    } else {
      // Directly set media URL for playback from remote source
      setMediaUrl(mediaUrl);
      setMediaType(mediaType);
    }
  };

  const subscribeToChannel = (shortUuid) => {
    pubnub.addListener({
      message: async (message) => {
        try {
          if (message && message.message) {
            const messageContent = JSON.parse(message.message);
            handleMediaPlayback(messageContent);
            await AsyncStorage.setItem('mediaUrl', messageContent.mediaUrl);
            await AsyncStorage.setItem('mediaType', messageContent.mediaType);
          } else {
            console.warn('Received message with missing message property:', message);
          }
        } catch (error) {
          console.error('Error parsing message:', error);
        }
      },
    });

    pubnub.subscribe({ channels: [`screenvu_${shortUuid}`] });
  };
console.log("problem he ",mediaUrl)
console.log("problem2  he ",mediaType)
console.log("ref",videoRef.current)
  return (
    <View style={styles.container}>
    {loading ? (
      <>
      <Text style={styles.progressText}>{Math.round(progress)}%</Text>
      </>
   
    ) : mediaUrl ? (
      mediaType === 'VIDEO' ? (
        <Video
         ref={videoRef}
          source={{ uri: mediaUrl }}
          style={styles.media}
          controls={false}
          resizeMode="contain"
          repeat={true}
          autoplay={true}
        />
        // <Text style={{color:'red'}}>{mediaUrl}{mediaType}</Text>
      ) : (
        <Image source={{ uri: mediaUrl }} style={styles.media} />
      )
    ) : (
      <React.Fragment>
        <Image source={require('./assets/logo.png')} style={styles.logo} />
        <View style={{ height: 30 }}></View>
        <View style={{ backgroundColor: 'white', justifyContent: 'center', alignItems: 'center', paddingHorizontal: 35, paddingVertical: 4 }}>
          <Text style={{ color: '#1846b1', fontWeight: 'bold', fontSize: 16 }}>{displayID}</Text>
        </View>
      </React.Fragment>
    )}
  </View>
);
  
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
  },
  mediaContainer: {
    width: Dimensions.get('window').width,
    height: Dimensions.get('window').height,
    backgroundColor: '#f6f6f6',
  },
  media: {
    flex: 1,
    width: '100%',
    height: '100%',
  },
  button: {
    marginTop: 20,
    padding: 10,
    backgroundColor: 'blue',
    borderRadius: 5,
  },
  buttonText: {
    color: 'white',
    fontSize: 16,
  },
  logo: {
    height: 100,
    width: 100,
  },
  loaderContainer: {
    justifyContent: 'center',
    alignItems: 'center',
  },
  progressText: {
    fontSize: 16,
    color:"blue",
    alignSelf:'center',
    justifyContent:'center'
  },
});

export default HomeScreen;

I tried to handle by useRef
tried set State is useEffect

New contributor

SHUBHAM SONAR 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