Persistência de dados local
Aprenda vários métodos para armazenar e gerir dados localmente em dispositivos móveis, incluindo SQLite, AsyncStorage e preferências partilhadas.
Persistência de dados local é uma aula grátis de Indie Hacker Mobile Apps no CoddyKit. Esta é a aula 2 de 4. Você pode ler a aula completa abaixo gratuitamente — depois pratica ao vivo no navegador com um editor de código integrado e um tutor de IA 24/7. Faz parte do caminho de aprendizado de Indie Hacker Mobile Apps, e seu progresso é sincronizado entre a web e o app CoddyKit. O curso de Indie Hacker Mobile Apps inclui 4 aulas no total.
Partes desta aula ainda não foram traduzidas e aparecem em inglês.
Why Store Data Locally?
When building mobile apps, some data needs to be available even when there's no internet connection. This is where local data persistence comes in!
It means storing information directly on the user's device, rather than always fetching it from a server.
Benefits of Local Storage
Storing data locally offers several advantages for your app:
- Offline Access: Users can still use core features without internet.
- Faster Performance: Retrieving data from the device is quicker than from a remote server.
- Improved UX: A smoother, more responsive experience for your users.
- Personalization: Saving user preferences and settings.
Simple Key-Value Pairs
One of the easiest ways to store small amounts of data is using key-value pairs. Think of it like a dictionary or a map where each piece of data has a unique name (the 'key') and its corresponding value.
This is perfect for user settings, feature flags, or simple flags like 'has seen onboarding'.
Shared Preferences (Android/iOS)
On native platforms, Android uses Shared Preferences and iOS uses UserDefaults for key-value storage. They work similarly:
- Store simple data types (strings, numbers, booleans).
- Are often synchronous.
- Best for small amounts of non-sensitive data.
For cross-platform frameworks, you'll use an abstraction layer.
AsyncStorage: Cross-Platform K-V
For apps built with frameworks like React Native, AsyncStorage is a popular module for local key-value storage. It's an asynchronous, unencrypted, persistent key-value storage system.
Because it's asynchronous, your app won't freeze while data is being read or written.
Saving Data with AsyncStorage
Here's how you might conceptually save a user's theme preference using AsyncStorage. In a real app, AsyncStorage would be imported from a library.
// (Imagine AsyncStorage is globally available)
async function main() {
console.log("Attempting to save user theme...");
try {
// In a real app, this would save to device storage.
// await AsyncStorage.setItem('userTheme', 'dark');
console.log("User theme 'dark' conceptually saved.");
} catch (error) {
console.log("Error saving data:", error.message);
}
}
main();Reading Data with AsyncStorage
To retrieve the saved data, you use the getItem method. It also returns a Promise, so you'll typically use await or .then().
// (Imagine AsyncStorage is globally available)
async function main() {
console.log("Attempting to read user theme...");
try {
// In a real app, this would read from device storage.
// const theme = await AsyncStorage.getItem('userTheme');
const theme = "dark"; // Simulate a retrieved value
console.log("Retrieved user theme:", theme);
} catch (error) {
console.log("Error reading data:", error.message);
}
}
main();SQLite: Relational Database
For more complex data, like lists of items, user profiles with multiple fields, or anything requiring structured queries, SQLite is a powerful option.
It's a lightweight, embedded relational database that runs directly on the device. Think of it as a mini-serverless database.
When to Use SQLite
SQLite is ideal when you need:
- Structured Data: Tables, columns, and relationships.
- Complex Queries: Filtering, sorting, joining data.
- Large Datasets: More efficient than key-value for many items.
- Offline Sync: Storing data that will eventually sync with a backend.
However, it adds more complexity to your app's architecture.
Quick Check: Data Storage
Which local data storage method is generally best suited for storing a user's preference for 'dark mode' in a cross-platform mobile app?
Recap: Local Data Persistence
You've learned about essential local data persistence techniques for mobile apps!
- Key-Value Stores: Simple for small data (Shared Preferences/UserDefaults, AsyncStorage).
- AsyncStorage: Cross-platform (React Native) key-value, asynchronous.
- SQLite: Embedded relational database for structured, complex data.
Choosing the right method depends on your data's complexity and your app's specific needs. Next, we'll explore integrating with remote APIs!
Perguntas Frequentes
A aula “Persistência de dados local” é grátis?
Sim — o texto completo de “Persistência de dados local” é grátis para ler aqui na web. Para praticá-la interativamente (um editor de código integrado e um tutor de IA 24/7) e desbloquear o restante do curso de Indie Hacker Mobile Apps, atualize para CoddyKit PRO. O curso de Indie Hacker Mobile Apps inclui 4 aulas no total.
O que vou aprender em “Persistência de dados local”?
Aprenda vários métodos para armazenar e gerir dados localmente em dispositivos móveis, incluindo SQLite, AsyncStorage e preferências partilhadas. Você pratica Indie Hacker Mobile Apps com código prático que executa diretamente no navegador, e um tutor de IA 24/7 responde suas dúvidas enquanto trabalha na aula.
Preciso ter experiência prévia para começar Indie Hacker Mobile Apps?
Nenhuma experiência prévia é necessária. Indie Hacker Mobile Apps no CoddyKit é estruturado para alunos iniciantes até avançados, então você pode começar aqui ou desde o início e aprender no seu ritmo. Esta é a aula 2 de 4.
Quanto tempo leva a aula “Persistência de dados local”?
A maioria das aulas CoddyKit leva cerca de 5–10 minutos. Cada uma é compacta e interativa, então você faz progresso constante e retoma exatamente de onde parou entre web e app.
Posso escrever e executar código nesta aula de Indie Hacker Mobile Apps?
Sim. Cada aula de Indie Hacker Mobile Apps inclui um editor de código integrado, então você escreve e executa código real direto no navegador e recebe feedback de IA instantaneamente — nenhuma configuração local necessária.
Todas as aulas deste curso
- Gestão de estado para aplicações móveis
- Persistência de dados local
- Integração de APIs RESTful
- Arquitetura de navegação e roteamento