Skip to content
Snippets Groups Projects
delete-data.js 2.73 KiB
Newer Older
import React, { Component } from 'react'
import RNFS from 'react-native-fs'
MariaZ's avatar
MariaZ committed
import { Alert } from 'react-native'
mashazyu's avatar
mashazyu committed
import PropTypes from 'prop-types'
import Button from '../../common/button'

Maria Zadnepryanets's avatar
Maria Zadnepryanets committed
import ConfirmWithPassword from '../common/confirm-with-password'
import alertError from '../common/alert-error'
import { clearDb, isDbEmpty } from '../../../db'
import { showToast } from '../../helpers/general'
import { hasEncryptionObservable } from '../../../local-storage'
import settings from '../../../i18n/en/settings'
import { shared as sharedLabels } from '../../../i18n/en/labels'
import { EXPORT_FILE_NAME } from './constants'
const exportedFilePath = `${RNFS.DocumentDirectoryPath}/${EXPORT_FILE_NAME}`

export default class DeleteData extends Component {
  constructor() {
    super()
    this.state = {
      isPasswordSet: hasEncryptionObservable.value,
      isConfirmingWithPassword: false
  onAlertConfirmation = () => {
mashazyu's avatar
mashazyu committed
    this.props.onStartDeletion()
    if (this.state.isPasswordSet) {
      this.setState({ isConfirmingWithPassword: true })
    } else {
      this.deleteAppData()
  alertBeforeDeletion = async () => {
    const { question, message, confirmation, errors } = settings.deleteSegment
    if (isDbEmpty() && !await RNFS.exists(exportedFilePath)) {
      alertError(errors.noData)
    } else {
      Alert.alert(
        question,
        message,
        [{
          text: confirmation,
          onPress: this.onAlertConfirmation
        }, {
          text: sharedLabels.cancel,
          style: 'cancel',
          onPress: this.cancelConfirmationWithPassword
        }]
      )
    }
  }

  deleteExportedFile = async () => {
    if (await RNFS.exists(exportedFilePath)) {
      await RNFS.unlink(exportedFilePath)
    }
  }

  deleteAppData = async () => {
    const { errors, success } = settings.deleteSegment
      await this.deleteExportedFile()
      showToast(success.message)
    } catch (err) {
  cancelConfirmationWithPassword = () => {
    this.setState({ isConfirmingWithPassword: false })
    const { isConfirmingWithPassword } = this.state
mashazyu's avatar
mashazyu committed
    const { isDeletingData } = this.props
mashazyu's avatar
mashazyu committed
    if (isConfirmingWithPassword && isDeletingData) {
      return (
        <ConfirmWithPassword
          onSuccess={this.deleteAppData}
          onCancel={this.cancelConfirmationWithPassword}
        />
Maria Zadnepryanets's avatar
Maria Zadnepryanets committed
      <Button isCTA onPress={this.alertBeforeDeletion}>
        {settings.deleteSegment.title}
mashazyu's avatar
mashazyu committed
}

DeleteData.propTypes = {
  isDeletingData: PropTypes.bool,
  onStartDeletion: PropTypes.func.isRequired
MariaZ's avatar
MariaZ committed
}