Search code examples
reactjsreact-nativebackground-process

react-native-background-timer, null is not an object


I've got an error using react-native-background-timer. I would be appreciate it if you could help me solve this problem.

I'm developing a mobile app on Expo Snack, and I now want to realize the auto-delete-account function: when an account is created and not being verified for 5 minutes, it will be deleted automatically. So, I searched about background timer and I found the library below.

https://github.com/ocetnik/react-native-background-timer

However, I wasn't able to achieve it because of the error below

(3:2693) null is not an object (evaluating 'o.setTimeout')

and this is my code

import React, { Component } from 'react';
import { View, Text, TouchableOpacity, Platform } from 'react-native';
import BackgroundTimer from 'react-native-background-timer';

let counter = 0;
let timer = null;

export default class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      second: 0,
    };
  }
  _interval: any;

  onStart = () => {
    if (Platform.OS == 'ios') {
      BackgroundTimer.start();
    }

    this._interval = BackgroundTimer.setInterval(() => {
      this.setState({
        second: this.state.second + 1,
      });
    }, 1000);
  };

  onPause = () => {
    BackgroundTimer.clearInterval(this._interval);
  };

  onReset = () => {
    this.setState({
      second: 0,
    });
    BackgroundTimer.clearInterval(this._interval);
  };
  render() {
    return (
      <View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}>
        <TouchableOpacity onPress={this.onStart}>
          <Text>start</Text>
        </TouchableOpacity>
        <TouchableOpacity onPress={this.onPause}>
          <Text>pause</Text>
        </TouchableOpacity>
        <TouchableOpacity onPress={this.onReset}>
          <Text>reset</Text>
        </TouchableOpacity>
        <Text>{this.state.second}</Text>
      </View>
    );
  }
}

I followed a tutorial of this guy https://medium.com/@loons.create/how-to-setup-react-native-background-timer-22263d655847

The equipped function, setInterval of javascript and etc. of course works fine as a timer, but actually they don't work behind in react native.

What am I missing, or is this an issue inside this library( I suppose so )? If so, please tell me an available version of this library; I use the latest version, 2.2.0, and React v35.0.0

Thank you


Solution

  • You cannot use "react-native-background-timer" with Expo on managed workflow. This library needs to compile some native code.

    Instead, you should take a took to Expo BackgroundFetch which is doing almost the same thing.

    https://docs.expo.io/versions/latest/sdk/background-fetch/

    Using Expo components, you don't need to eject or compile additional native code.