Search code examples
javascriptreactjsreact-nativeactivity-indicatorreact-native-push-notification

ActivityIndicator not working in react native


I am working with react-native-push-notification. On button click, I want to delete local notification created earlier and I am able to do that using PushNotification.cancelLocalNotifications({id: '123'}). I want to show activity indicator while notifications are deleting but I am facing problem.

Here is my code. This method is triggered when button is clicked :

import React from 'react';
import {
    View,
    Text,
    Button,
    ActivityIndicator,
} from 'react-native';
import PushNotification from 'react-native-push-notification';

export default class App extends React.Component {

    constructor() {
        super();
        this.state = {
            spinner: false,
        }
    }

    delete = (id) => {
        this.setState({ spinner: true });
        var userid = id;
        var temp = 0;
        //I want to start my activity Indicator here
        for (let i = 0; i < 50; i++) {
            temp = Number(userid) + Number(i);
            PushNotification.cancelLocalNotifications({
                id: temp,
            });
        }
        this.setState({ spinner: false });
        // I want to stop my activity Indicator here
    }

    render() {

        if (this.state.spinner) {

            return (
                <View style={{ flex: 1, justifyContent: 'center' }}>
                    <ActivityIndicator/>
                </View>
            );
        } else {
            return (
                <View>
                    //code snippet
                    <TouchableOpacity onPress={() => this.delete(id)}>
                        <Text>click</Text>
                    </TouchableOpacity>
                </View>);
        }
    }
}


Solution

  • Here delete function is asynchronous, so, for-loop may start before this.setState({ spinner: true });

    or this.setState({ spinner: false }); may run immediately after this.setState({ spinner: true }); while for-loop keeps running.

    You can set your spinner variable in for-loop:

    delete = (id) => {
            var userid = id;
            var temp = 0;
            for (let i = 0; i < 50; i++) {
                if (i == 0) {
                    //start indicator here
                    this.setState({ spinner: true });
                }
                temp = Number(userid) + Number(i);
                PushNotification.cancelLocalNotifications({
                    id: temp,
                });
                if (i == 49) {
                    //end indicator here
                    this.setState({ spinner: false });
                }
            }
        }