Lewati ke isi
Sabtu, 7 November 2026 Tutorial & berita teknologi Tentang Kontak
Komputerkampus.com
Tutorial Android & React Native Basic React Native · Bab 29 dari 30

Basic React Native Part 29 - React Native AsyncStorage

PadaPart 28 [/basic-react-native-part-28-react-native-copy-to-clipboard/]kita telah belajar dan mengenal Copy To Clipboard jadi jika anda belum mengikuti tutorial Part 28 [/basic-react-native-part-28-react-native-copy-to-clipboard/] diharap…

Daftar isi 5 bagian
  1. Mengimplementasikan Pada Project React Native
  2. Buat Project React Native
  3. Install Aplikasi Debug Ke Handphone Android
  4. Buka File App.js Dengan Visual Studio Code
  5. Menghapus Code Default App.js

Pada  Part 28 kita telah belajar dan mengenal Copy To Clipboard jadi jika anda belum mengikuti tutorial Part 28 diharapkan anda mengikuti tutorial Part 28 terlebih dahulu. Pada Tutorial Part 29 ini kita mengenal terlebih dahulu Basic React Native AsyncStorage.

Ketika kita membuat sebuah aplikasi mobile, akan ada suatu kondisi di mana kita perlu menyimpan data di perangkat user. React native memiliki API khusus untuk melakukan hal ini yaitu AsyncStorage merupakan sistem penyimpanan sederhana tak terenkripsi.

Mengimplementasikan Pada Project React Native

Buat Project React Native

Pada Tutorial Part 2 kita telah menginstall react-native-cli kemudian kita telah belajar cara membuat project baru react native. Berikut perintah cara untuk membuat project baru react native.

react-native init namafolderproject

Buat Project Baru

Install Aplikasi Debug Ke Handphone Android

Pada Tutorial Part 4 kita telah belajar cara menginstall Aplikasi Debug ke Handphone Android, untuk tata cara yang lebih jelas bisa langsung pelajari lagi pada Tutorial Part 4 terlebih dahulu. Secara singkat perintahnya seperti berikut.

react-native run-android

Install Aplikasi Debug Ke Handphone Android

Buka File App.js Dengan Visual Studio Code

Secara default pada file App.js memiliki code yang cukup dan menghasilkan tampilkan seperti berikut ini

import React from 'react';
import {
  SafeAreaView,
  StyleSheet,
  ScrollView,
  View,
  Text,
  StatusBar,
} from 'react-native';

import {
  Header,
  LearnMoreLinks,
  Colors,
  DebugInstructions,
  ReloadInstructions,
} from 'react-native/Libraries/NewAppScreen';

const App: () => React$Node = () => {
  return (
    <>
      <StatusBar barStyle="dark-content" />
      <SafeAreaView>
        <ScrollView
          contentInsetAdjustmentBehavior="automatic"
          style={styles.scrollView}>
          <Header />
          {global.HermesInternal == null ? null : (
            <View style={styles.engine}>
              <Text style={styles.footer}>Engine: Hermes</Text>
            </View>
          )}
          <View style={styles.body}>
            <View style={styles.sectionContainer}>
              <Text style={styles.sectionTitle}>Step One</Text>
              <Text style={styles.sectionDescription}>
                Edit <Text style={styles.highlight}>App.js</Text> to change this
                screen and then come back to see your edits.
              </Text>
            </View>
            <View style={styles.sectionContainer}>
              <Text style={styles.sectionTitle}>See Your Changes</Text>
              <Text style={styles.sectionDescription}>
                <ReloadInstructions />
              </Text>
            </View>
            <View style={styles.sectionContainer}>
              <Text style={styles.sectionTitle}>Debug</Text>
              <Text style={styles.sectionDescription}>
                <DebugInstructions />
              </Text>
            </View>
            <View style={styles.sectionContainer}>
              <Text style={styles.sectionTitle}>Learn More</Text>
              <Text style={styles.sectionDescription}>
                Read the docs to discover what to do next:
              </Text>
            </View>
            <LearnMoreLinks />
          </View>
        </ScrollView>
      </SafeAreaView>
    </>
  );
};

const styles = StyleSheet.create({
  scrollView: {
    backgroundColor: Colors.lighter,
  },
  engine: {
    position: 'absolute',
    right: 0,
  },
  body: {
    backgroundColor: Colors.white,
  },
  sectionContainer: {
    marginTop: 32,
    paddingHorizontal: 24,
  },
  sectionTitle: {
    fontSize: 24,
    fontWeight: '600',
    color: Colors.black,
  },
  sectionDescription: {
    marginTop: 8,
    fontSize: 18,
    fontWeight: '400',
    color: Colors.dark,
  },
  highlight: {
    fontWeight: '700',
  },
  footer: {
    color: Colors.dark,
    fontSize: 12,
    fontWeight: '600',
    padding: 4,
    paddingRight: 12,
    textAlign: 'right',
  },
});

export default App;

Code Default App.js

Tampilan Default File App.js

Tampilan Default File App.js

Menghapus Code Default App.js

Untuk memudahkan memahami component AsyncStorage kita hapus semua code dafault App.js. Setelah semua code default App.js dihapus maka ikuti langkah - langkah berikut ini.

  • Import React
import React, { Component } from 'react';

import react

  • Import Component Yang ingin digunakan
import AsyncStorage from '@react-native-community/async-storage'
import { StyleSheet, View, TextInput, Button, Alert, Text, TouchableOpacity } from 'react-native';

Import Component

  • Membuat Class Componet
class App extends Component {
  render() { 
    return (  );
  }
}
 

Membuat Class

  • Kemudian tambahkan code berikut ini diatas render
//Tambahkan code ini diatas render
constructor() {
    super();
    this.state = {
      textInputData: '',
      getValue: '',
    };
  }
  saveValueFunction = () => {
    if(this.state.textInputData){
      AsyncStorage.setItem('any_key_here', this.state.textInputData);
      this.setState({ textInputData: '' })
      alert('Data Saved');
    }else{
      alert('Please fill data');
    }
  };
  getValueFunction = () => {
    AsyncStorage.getItem('any_key_here').then(value =>
      this.setState({ getValue: value })
    );
  };

Code Diatas Render

  • Kemudian tambahan code berikut ini didalam return.
return (
    //Code return
<View style={styles.MainContainer}>
        <TextInput
          placeholder="Enter Some Text here"
          value={this.state.textInputData}
          onChangeText={data => this.setState({ textInputData: data })}
          underlineColorAndroid="transparent"
          style={styles.TextInputStyle}
        />
        <TouchableOpacity
          onPress={this.saveValueFunction}
          style={styles.button}>
          <Text style={styles.buttonText}> SAVE VALUE </Text>
        </TouchableOpacity>
        <TouchableOpacity
          onPress={this.getValueFunction}
          style={styles.button}>
          <Text style={styles.buttonText}> GET VALUE </Text>
        </TouchableOpacity>
        <Text style={styles.text}> {this.state.getValue} </Text>
      </View>
)

Tambahkan code pada return

  • Setelah itu export class App.
export default App

export class

  • Berikut code style, letakkan sebelum export default
//Buat Style
const styles = StyleSheet.create({
  MainContainer: {
    alignItems: 'center',
    flex: 1,
    margin: 10,
    marginTop:60
  },
  TextInputStyle: {
    textAlign: 'center',
    height: 40,
    width: '100%',
    borderWidth: 1,
    borderColor: '#808000',
  },
  button: {
    width: '100%',
    height: 40,
    padding: 10,
    backgroundColor: '#808000',
    marginTop: 10,
  },
  buttonText: {
    color: '#fff',
    textAlign: 'center',
  },
  text: {
    fontSize: 20,
    textAlign: 'center',
  },
});

Code Style

  • Berikut Code lengkap nya
import React, { Component } from 'react';
import AsyncStorage from '@react-native-community/async-storage'
import { StyleSheet, View, TextInput, Button, Alert, Text, TouchableOpacity } from 'react-native';
 
class App extends Component {
  constructor() {
    super();
    this.state = {
      textInputData: '',
      getValue: '',
    };
  }
  saveValueFunction = () => {
    if(this.state.textInputData){
      AsyncStorage.setItem('any_key_here', this.state.textInputData);
      this.setState({ textInputData: '' })
      alert('Data Saved');
    }else{
      alert('Please fill data');
    }
  };
  getValueFunction = () => {
    AsyncStorage.getItem('any_key_here').then(value =>
      this.setState({ getValue: value })
    );
  };
  render() {
    return (
      <View style={styles.MainContainer}>
        <TextInput
          placeholder="Enter Some Text here"
          value={this.state.textInputData}
          onChangeText={data => this.setState({ textInputData: data })}
          underlineColorAndroid="transparent"
          style={styles.TextInputStyle}
        />
        <TouchableOpacity
          onPress={this.saveValueFunction}
          style={styles.button}>
          <Text style={styles.buttonText}> SAVE VALUE </Text>
        </TouchableOpacity>
        <TouchableOpacity
          onPress={this.getValueFunction}
          style={styles.button}>
          <Text style={styles.buttonText}> GET VALUE </Text>
        </TouchableOpacity>
        <Text style={styles.text}> {this.state.getValue} </Text>
      </View>
    );
  }
}
const styles = StyleSheet.create({
  MainContainer: {
    alignItems: 'center',
    flex: 1,
    margin: 10,
    marginTop:60
  },
  TextInputStyle: {
    textAlign: 'center',
    height: 40,
    width: '100%',
    borderWidth: 1,
    borderColor: '#808000',
  },
  button: {
    width: '100%',
    height: 40,
    padding: 10,
    backgroundColor: '#808000',
    marginTop: 10,
  },
  buttonText: {
    color: '#fff',
    textAlign: 'center',
  },
  text: {
    fontSize: 20,
    textAlign: 'center',
  },
});
export default App

Code Lengkap

  • Tampilan AsyncStorage

Tampilan Copy to Clipboard

Tampilan AsyncStorage

Demikianlah pembahasan Tutorial Part 29 ini akan kita lanjutkan pada Tutorial Part 30.


Catatan: tulisan ini dipindahkan dari cloudborneo.com, terbit pertama 21 Januari 2020.

Bagikan WhatsApp Telegram X

Tentang penulis

Wandi Pratama
Wandi Pratama

Saya seorang Developer Mobile menggunakan Framework React Native dan saya juga memiliki pengalaman dibidang SYS Admin. Jasa menerima jasa pembuatan aplikasi dan website https://pindahdigital.com

Tulisan lainnya

Terkait