React Native – Banco de Dados AsyncStorage

React Native – Banco de Dados AsyncStorage

Neste exemplo iremos mostrar como utilizar um banco de dados AsyncStorage no react native.

App.js

import React, { Component } from 'react';
import { TextInput, Button, StyleSheet, Text, View, ScrollView, Keyboard, TouchableOpacity } from 'react-native';
import { saveSettings, loadSettings, removeSettings } from './storage/settingsStorage';


export default class Apps extends React.Component {
  constructor(props) {
    super(props);
  
    this.state = { 
      name: '',
      fone: ''
   }
    this.handleSubmit = this.handleSubmit.bind(this);
    this.handleNameChange = this.handleNameChange.bind(this);
    this.handleFoneChange = this.handleFoneChange.bind(this);
    this.getTudo = this.getTudo.bind(this);

  }
  handleNameChange(name) {
    this.setState({ name });
  }
  handleFoneChange(fone) {
    this.setState({ fone });
  }
  handleSubmit() {
    saveSettings(this.state);
  }
  async componentDidMount() {
    const initialState = await loadSettings();
  
    this.setState(initialState);
  }

  async getTudo() {
    try {
      const initialState = await loadSettings();
      //const {name, fone} = initialState
      //this.setState({name, fone});
      this.setState(initialState);
    } catch (error) {
      console.log("Error retrieving data" + error);
    }
  }

  async removeName() {
    try {
      await removeSettings();
      this.getTudo().bind(this);
    } catch (error) {
      console.log("Error retrieving data" + error);
    }
  }

  render() {
    return (
      <View style={styles.container}>
        <View>
          <Text style={styles.header}>Settings</Text>
        </View>
        <ScrollView>
          <View style={styles.inputContainer}>
            <TextInput
              style={styles.textInput}
              placeholder="Your name"
              maxLength={20}
              onBlur={Keyboard.dismiss}
              value={this.state.name}
              onChangeText={this.handleNameChange}
            />
            <TextInput
              style={styles.textInput}
              placeholder="Your fone"
              maxLength={20}
              onBlur={Keyboard.dismiss}
              value={this.state.fone}
              onChangeText={this.handleFoneChange}
            />
          </View>
          <View style={styles.inputContainer}>
            <TouchableOpacity
              style={styles.saveButton}
              onPress={this.handleSubmit}
            >
              <Text style={styles.saveButtonText}>Save</Text>
            </TouchableOpacity>
            <Button
              style={styles.saveButton}
              onPress={this.getTudo}
              title="Get"
              color="#2196f3"
              accessibilityLabel="Print Name"
            />
            <Button
              style={styles.saveButton}
              onPress={this.removeName.bind(this)}
              title="Remove"
              color="#2196f3"
              accessibilityLabel="Remove Name"
            />
          </View>
          <View>
          <Text>
               {this.state.name}
            </Text>
            <Text>
               {this.state.fone}
            </Text>
          </View>
        </ScrollView>
      </View>
      
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    paddingTop: 45,
    backgroundColor: '#F5FCFF',
  },
  header: {
    fontSize: 25,
    textAlign: 'center',
    margin: 10,
    fontWeight: 'bold'
  },
  inputContainer: {
    paddingTop: 15
  },
  textInput: {
    borderColor: '#CCCCCC',
    borderTopWidth: 1,
    borderBottomWidth: 1,
    height: 50,
    fontSize: 25,
    paddingLeft: 20,
    paddingRight: 20
  },
  saveButton: {
    borderWidth: 1,
    borderColor: '#007BFF',
    backgroundColor: '#007BFF',
    padding: 15,
    margin: 10
  },
  saveButtonText: {
    color: '#FFFFFF',
    fontSize: 20,
    textAlign: 'center'
  }
});

settingsStorage.js

import { AsyncStorage } from 'react-native';

const STORAGE_KEY = 'SETTINGS';

export const saveSettings = (settings) => {
  //AsyncStorage.setItem(STORAGE_KEY, JSON.stringify(settings));
  AsyncStorage.multiSet(settings)
  
}

export const removeSettings = (settings) => {
  AsyncStorage.removeItem(STORAGE_KEY);
}

const DEFAULT_SETTINGS = {
  name: '',
  fone: ''
};

export const loadSettings = async () => {
  try {
    let settings = await AsyncStorage.getItem(STORAGE_KEY);

    if (settings === null) { return DEFAULT_SETTINGS; }

    return JSON.parse(settings);
  } catch (error) {
    console.log('Error loading settings', error);
  }
}

Deixe uma resposta

Specify Google Client ID and Secret in Super Socializer > Social Login section in admin panel for Google Login to work

O seu endereço de e-mail não será publicado. Campos obrigatórios são marcados com *