Why is Firestore creating new user on every reload

Viewed 33

I am trying to make a Todo/Notes App with Firebase as DB. The app is working perfectly in sync with the FirestoreDB, but every time I close and reopen the app, the app seems to delete the previous credentials and create a new user altogether and all the previous notes are gone from the app, which still exist on the FirestoreDB. Can anyone tell me what am I doing wrong?

This is the App.js

import {
    StyleSheet,
    Text,
    View,
    TouchableOpacity,
    FlatList,
    Modal,
    ActivityIndicator,
} from 'react-native';
import colors from './Colors';
import { AntDesign } from '@expo/vector-icons';
import TodoList from './components/TodoList';
import AddListModal from './components/AddListModal';
import Fire from './Fire';

export default class App extends React.Component {
    state = {
        addTodoVisibile: false,
        lists: [],
        user: {},
        loading: true,
    };

    componentDidMount() {
        firebase = new Fire((error, user) => {
            if (error) {
                return alert('Something went wrong');
            }

            firebase.getLists(lists => {
                this.setState({ lists, user }, () => {
                    this.setState({ loading: false });
                });
            });

            this.setState({ user });
        });
    }

    componentWillUnmount() {
        firebase.detach();
    }

    toggleAddTodoModal() {
        this.setState({ addTodoVisibile: !this.state.addTodoVisibile });
    }

    renderList = list => {
        return <TodoList list={list} updateList={this.updateList} />;
    };

    addList = list => {
        firebase.addList({
            name: list.name,
            color: list.color,
            todos: [],
        });
    };

    updateList = list => {
        firebase.updateList(list);
    };

    deleteList = list => {
        firebase.deleteList(list);
    };

    renderList = list => {
        return (
            <TodoList
                list={list}
                updateList={this.updateList}
                deleteList={this.deleteList}
            />
        );
    };

    render() {
        if (this.state.loading) {
            return (
                <View style={styles.container}>
                    <ActivityIndicator size={50} color={colors.highlight} />
                </View>
            );
        }
        return (
            <View style={styles.container}>
                <Modal
                    animationType='slide'
                    visible={this.state.addTodoVisibile}
                    onRequestClose={() => this.toggleAddTodoModal()}
                >
                    <AddListModal
                        closeModal={() => this.toggleAddTodoModal()}
                        addList={this.addList}
                    />
                </Modal>

                <View style={{ flexDirection: 'row' }}>
                    <View style={styles.divider} />
                    <Text style={styles.title}>
                        Post
                        <Text
                            style={{
                                fontWeight: '500',
                                color: colors.highlight,
                            }}
                        >
                            It
                        </Text>
                    </Text>
                    <View style={styles.divider} />
                </View>
                <View style={{ marginVertical: 48 }}>
                    <TouchableOpacity
                        style={styles.addList}
                        onPress={() => this.toggleAddTodoModal()}
                    >
                        <AntDesign name='plus' size={25} color={colors.white} />
                    </TouchableOpacity>

                    <Text style={styles.add}>Add a List</Text>
                </View>
                <View style={{ height: 275 }}>
                    <FlatList
                        data={this.state.lists}
                        keyExtractor={item => item.id.toString()}
                        horizontal={true}
                        showsHorizontalScrollIndicator={false}
                        renderItem={({ item }) => this.renderList(item)}
                        keyboardShouldPersistTaps='always'
                    />
                </View>
                <Text style={styles.delete}>
                    <Text style={styles.highlight}>(</Text>
                    Long Press on List to Delete
                    <Text style={styles.highlight}>)</Text>
                </Text>
            </View>
        );
    }
}

const styles = StyleSheet.create({
    container: {
        flex: 1,
        backgroundColor: colors.background,
        alignItems: 'center',
        justifyContent: 'center',
    },
    divider: {
        backgroundColor: colors.highlight,
        height: 1,
        flex: 1,
        alignSelf: 'center',
    },
    title: {
        fontSize: 38,
        fontWeight: '800',
        color: colors.white,
        paddingHorizontal: 64,
    },
    addList: {
        borderWidth: 2,
        borderColor: colors.highlight,
        borderRadius: 4,
        padding: 16,
        alignItems: 'center',
    },
    add: {
        color: colors.white,
        fontWeight: '600',
        fontSize: 16,
        marginTop: 8,
    },
    delete: {
        color: colors.white,
        fontWeight: '500',
        fontSize: 12.5,
        position: 'absolute',
        bottom: 8,
    },
    highlight: {
        color: colors.highlight,
    },
});

and this is Fire.js

import 'firebase/compat/firestore';
import 'firebase/compat/auth';

const firebaseConfig = {
    
};
class Fire {
    constructor(callback) {
        this.init(callback);
    }
    init(callback) {
        if (!firebase.apps.length) {
            firebase.initializeApp(firebaseConfig);
        }

        firebase.auth().onAuthStateChanged(user => {
            if (user) {
                callback(null, user);
            } else {
                firebase
                    .auth()
                    .signInAnonymously()
                    .catch(error => {
                        callback(error);
                    });
            }
        });
    }
    getLists(callback) {
        let ref = this.ref.orderBy('name');

        this.unsubscribe = ref.onSnapshot(snapshot => {
            lists = [];

            snapshot.forEach(doc => {
                lists.push({ id: doc.id, ...doc.data() });
            });

            callback(lists);
        });
    }

    addList(list) {
        let ref = this.ref;

        ref.add(list);
    }

    updateList(list) {
        let ref = this.ref;

        ref.doc(list.id).update(list);
    }

    deleteList(list) {
        let ref = this.ref;
        ref.doc(list.id).delete();
    }

    get userId() {
        return firebase.auth().currentUser.uid;
    }

    get ref() {
        return firebase
            .firestore()
            .collection('users')
            .doc(this.userId)
            .collection('lists');
    }

    detach() {
        this.unsubscribe();
    }
}

export default Fire;
1 Answers

On most environments the Firebase Authentication SDK will automatically persist the user credentials and restore them when the app/page is reloaded, and then call your onAuthStateChanged handler.

On React Native this is not possible by default though, so I recommend checking out the Firebase documentation on managing auth persistence..

Related