Home > database >  react functional component - render child - null property
react functional component - render child - null property

Time:01-23

i've got a problem with functional components and passing a service to child component I created a SoundAlarmService:

import { Audio } from 'expo-av';
class SoundAlamarService {

static readonly defaultSoundPath = require('../assets/1.wav');

private audioSound:Audio.Sound;


static CreateAsync = async(soundAsset = this.defaultSoundPath)=>{
    const {sound} = await Audio.Sound.createAsync(soundAsset);
    return new SoundAlamarService(sound);
}

private constructor(sound:Audio.Sound) {
    this.audioSound = sound;
}

play = async()=>{
    await this.audioSound.playAsync();
}

stop = async()=>{
    await this.audioSound.stopAsync(); 
}
}

export default SoundAlamarService;

and i creating it by useEffetct (tried once, but also not working) and then want to pass it to child component

export const MainTimer = () => {
  let alarmService:SoundAlarmService | null = null;
  const [initialized, setInitialized] = useState(false);

  useEffect(()=>{
     SoundAlarmService.CreateAsync().then(result=>{
      alarmService = result;
      setInitialized(true);
    })
  })
 
return !initialized 
  ? <></> 
  : (
    <View style={styles.container}>
         {timeConfired ? 
      <MainTimerAlarm soundService={alarmService} setTime={setTime} time={time} timeInfo={timer} stopped={!timeConfired} /> 
      :<></>}
      <SetMainTimer setTimer={setTimerFunc} setCancel={setCancel} />

    </View>
  ); 
}

i can debug and see it is assigned on UseEffect, but then on render method it is null how to fix that?

CodePudding user response:

timeConfired is not defined hence it is taking as null. Defining this variable in state and separating MainTimerAlarm from the functional component and rendering in a separate components will work.

CodePudding user response:

just moved declatarion of alarm service above functional component

let alarmService:SoundAlarmService;
export const MainTimer = () => {

  const [initialized, setInitialized] = useState(false);

  useEffect(()=>{
     SoundAlarmService.CreateAsync().then(result=>{
      alarmService = result;
      setInitialized(true);
    },[])
  })
  • Related