Search code examples
javascriptreactjsreact-nativereact-hooksreact-native-elements

react-native-element-timer useRef object is null


I am using the react-native-element-timer (https://www.npmjs.com/package/react-native-element-timer) and have a problem with the useRef hook.

The reference of timerRef is set with the rendering of the "Timer" element, but I want the timer to directly start when the function "Stopwatch" is called and not with onButtonClick. So i need to reference that Timer before it is rendered.

When I try it like this (see below), then an error occurs "TypeError: null is not an object (evaluating 'timerRef.current.start')".

export default function Stopwatch(item, process) {
    import React, { useRef } from 'react';
    import { Timer } from 'react-native-element-timer';


    const timerRef = useRef(null);

    //timerRef.current.start(); <--- this should be called with function Stopwatch

    return (
        <View >
            <Timer
                ref={timerRef}

                onTimes={e => { }}
                onEnd={e => { }}
            />
        </View>
    );
}

Any help is appreciated! Thanks

################

Update:

With

const timerRef = useRef(new Date) 

I get another error:

TypeError: timerRef.current.start is not a function. (In 'timerRef.current.start()', 'timerRef.current.start' is undefined)

Solution

  • This happens because you are calling timerRef.current.start(); in components body (and we don't know when this line code will be called by React, maybe before the ref is resolved).

    Much better use useEffect hook:

    const timerRef = useRef(null);
    
    useEffect(() => {
       if(timerRef.current) timerRef.current.start();
    }, [])
    

    In this way you are sure that timerRef.current is not undefined