import React, { useState } from 'react';
import { View, Text, TextInput, Button, StyleSheet } from 'react-native';
import { MMKV } from 'react-native-mmkv';
const storage = new MMKV();
export default function FastStorageDemo() {
const [input, setInput] = useState('');
const [savedValue, setSavedValue] = useState('');
const saveValue = () => {
if (input.trim() === '') {
alert('Please enter some text to save.');
return;
}
storage.set('myKey', input);
alert('Value saved!');
};
const loadValue = () => {
const value = storage.getString('myKey');
if (value === undefined) {
alert('No value found. Please save something first.');
setSavedValue('');
} else {
setSavedValue(value);
}
};
return (
<View style={styles.container}>
<Text style={styles.title}>Fast Storage Demo</Text>
<Text>Enter text:</Text>
<TextInput
style={styles.input}
value={input}
onChangeText={setInput}
placeholder="Type something"
accessibilityLabel="Input text field"
/>
<View style={styles.buttonRow}>
<Button title="Save" onPress={saveValue} />
<Button title="Load" onPress={loadValue} />
</View>
<Text>Saved value:</Text>
<Text style={styles.savedValue}>{savedValue}</Text>
</View>
);
}
const styles = StyleSheet.create({
container: { padding: 20, flex: 1, justifyContent: 'flex-start' },
title: { fontSize: 24, fontWeight: 'bold', marginBottom: 20 },
input: { borderWidth: 1, borderColor: '#ccc', padding: 10, marginVertical: 10, borderRadius: 5 },
buttonRow: { flexDirection: 'row', justifyContent: 'space-between', marginVertical: 10 },
savedValue: { fontSize: 18, marginTop: 10, color: '#333' }
});We created two functions: saveValue and loadValue. The saveValue function checks if the input is not empty, then saves it to MMKV storage with the key myKey. It shows an alert to confirm saving.
The loadValue function tries to get the stored string from MMKV. If nothing is found, it alerts the user and clears the displayed saved value. Otherwise, it updates the savedValue state to show the stored text.
These functions are connected to the Save and Load buttons respectively. The UI updates immediately when loading the saved value.
This example shows how MMKV provides a fast and simple way to store small pieces of data persistently in React Native apps.