Customize Consent Preferences

We use cookies to help you navigate efficiently and perform certain functions. You will find detailed information about all cookies under each consent category below.

The cookies that are categorized as "Necessary" are stored on your browser as they are essential for enabling the basic functionalities of the site. ... 

Always Active

Necessary cookies are required to enable the basic features of this site, such as providing secure log-in or adjusting your consent preferences. These cookies do not store any personally identifiable data.

No cookies to display.

Functional cookies help perform certain functionalities like sharing the content of the website on social media platforms, collecting feedback, and other third-party features.

No cookies to display.

Analytical cookies are used to understand how visitors interact with the website. These cookies help provide information on metrics such as the number of visitors, bounce rate, traffic source, etc.

No cookies to display.

Performance cookies are used to understand and analyze the key performance indexes of the website which helps in delivering a better user experience for the visitors.

No cookies to display.

Advertisement cookies are used to provide visitors with customized advertisements based on the pages you visited previously and to analyze the effectiveness of the ad campaigns.

No cookies to display.

Mejorando la App de Tareas con SQLite y Estilos en React Native

Tiempo de lectura: 2 minutos
Ciervos saltando - Pexels

En esta segunda parte, mejoraremos nuestra app de tareas de React Native con las siguientes mejoras:

  • Persistencia avanzada con SQLite.
  • Eliminación de tareas.
  • Interfaz mejorada con Styled Components.

Requisitos previos

1. Instalando SQLite

Expo proporciona un wrapper para SQLite, lo instalamos con:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
npx expo install expo-sqlite
npx expo install expo-sqlite
npx expo install expo-sqlite

Creamos un archivo database.js en src/utils/ para manejar la base de datos:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
import * as SQLite from 'expo-sqlite';
const db = SQLite.openDatabase('tasks.db');
export const setupDatabase = () => {
db.transaction(tx => {
tx.executeSql(
'CREATE TABLE IF NOT EXISTS tasks (id INTEGER PRIMARY KEY AUTOINCREMENT, text TEXT);'
);
});
};
export const getTasks = (callback) => {
db.transaction(tx => {
tx.executeSql('SELECT * FROM tasks;', [], (_, { rows }) => {
callback(rows._array);
});
});
};
export const addTask = (task, callback) => {
db.transaction(tx => {
tx.executeSql('INSERT INTO tasks (text) VALUES (?);', [task], () => {
getTasks(callback);
});
});
};
export const deleteTask = (id, callback) => {
db.transaction(tx => {
tx.executeSql('DELETE FROM tasks WHERE id = ?;', [id], () => {
getTasks(callback);
});
});
};
import * as SQLite from 'expo-sqlite'; const db = SQLite.openDatabase('tasks.db'); export const setupDatabase = () => { db.transaction(tx => { tx.executeSql( 'CREATE TABLE IF NOT EXISTS tasks (id INTEGER PRIMARY KEY AUTOINCREMENT, text TEXT);' ); }); }; export const getTasks = (callback) => { db.transaction(tx => { tx.executeSql('SELECT * FROM tasks;', [], (_, { rows }) => { callback(rows._array); }); }); }; export const addTask = (task, callback) => { db.transaction(tx => { tx.executeSql('INSERT INTO tasks (text) VALUES (?);', [task], () => { getTasks(callback); }); }); }; export const deleteTask = (id, callback) => { db.transaction(tx => { tx.executeSql('DELETE FROM tasks WHERE id = ?;', [id], () => { getTasks(callback); }); }); };
import * as SQLite from 'expo-sqlite';

const db = SQLite.openDatabase('tasks.db');

export const setupDatabase = () => {
  db.transaction(tx => {
    tx.executeSql(
      'CREATE TABLE IF NOT EXISTS tasks (id INTEGER PRIMARY KEY AUTOINCREMENT, text TEXT);'
    );
  });
};

export const getTasks = (callback) => {
  db.transaction(tx => {
    tx.executeSql('SELECT * FROM tasks;', [], (_, { rows }) => {
      callback(rows._array);
    });
  });
};

export const addTask = (task, callback) => {
  db.transaction(tx => {
    tx.executeSql('INSERT INTO tasks (text) VALUES (?);', [task], () => {
      getTasks(callback);
    });
  });
};

export const deleteTask = (id, callback) => {
  db.transaction(tx => {
    tx.executeSql('DELETE FROM tasks WHERE id = ?;', [id], () => {
      getTasks(callback);
    });
  });
};

2. Modificar la Pantalla para Usar SQLite

Editamos HomeScreen.js:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
import React, { useState, useEffect } from 'react';
import { View, Text, TextInput, Button, FlatList, TouchableOpacity } from 'react-native';
import { setupDatabase, getTasks, addTask, deleteTask } from '../utils/database';
export default function HomeScreen() {
const [task, setTask] = useState('');
const [tasks, setTasks] = useState([]);
useEffect(() => {
setupDatabase();
getTasks(setTasks);
}, []);
const handleAddTask = () => {
if (task.trim()) {
addTask(task, setTasks);
setTask('');
}
};
return (
<View style={{ padding: 20 }}>
<TextInput
placeholder="Nueva tarea"
value={task}
onChangeText={setTask}
style={{ borderBottomWidth: 1, marginBottom: 10 }}
/>
<Button title="Agregar" onPress={handleAddTask} />
<FlatList
data={tasks}
keyExtractor={(item) => item.id.toString()}
renderItem={({ item }) => (
<TouchableOpacity onPress={() => deleteTask(item.id, setTasks)}>
<Text>{item.text} ❌</Text>
</TouchableOpacity>
)}
/>
</View>
);
}
import React, { useState, useEffect } from 'react'; import { View, Text, TextInput, Button, FlatList, TouchableOpacity } from 'react-native'; import { setupDatabase, getTasks, addTask, deleteTask } from '../utils/database'; export default function HomeScreen() { const [task, setTask] = useState(''); const [tasks, setTasks] = useState([]); useEffect(() => { setupDatabase(); getTasks(setTasks); }, []); const handleAddTask = () => { if (task.trim()) { addTask(task, setTasks); setTask(''); } }; return ( <View style={{ padding: 20 }}> <TextInput placeholder="Nueva tarea" value={task} onChangeText={setTask} style={{ borderBottomWidth: 1, marginBottom: 10 }} /> <Button title="Agregar" onPress={handleAddTask} /> <FlatList data={tasks} keyExtractor={(item) => item.id.toString()} renderItem={({ item }) => ( <TouchableOpacity onPress={() => deleteTask(item.id, setTasks)}> <Text>{item.text} ❌</Text> </TouchableOpacity> )} /> </View> ); }
import React, { useState, useEffect } from 'react';
import { View, Text, TextInput, Button, FlatList, TouchableOpacity } from 'react-native';
import { setupDatabase, getTasks, addTask, deleteTask } from '../utils/database';

export default function HomeScreen() {
  const [task, setTask] = useState('');
  const [tasks, setTasks] = useState([]);

  useEffect(() => {
    setupDatabase();
    getTasks(setTasks);
  }, []);

  const handleAddTask = () => {
    if (task.trim()) {
      addTask(task, setTasks);
      setTask('');
    }
  };

  return (
    <View style={{ padding: 20 }}>
      <TextInput
        placeholder="Nueva tarea"
        value={task}
        onChangeText={setTask}
        style={{ borderBottomWidth: 1, marginBottom: 10 }}
      />
      <Button title="Agregar" onPress={handleAddTask} />
      <FlatList
        data={tasks}
        keyExtractor={(item) => item.id.toString()}
        renderItem={({ item }) => (
          <TouchableOpacity onPress={() => deleteTask(item.id, setTasks)}>
            <Text>{item.text} ❌</Text>
          </TouchableOpacity>
        )}
      />
    </View>
  );
}

3. Aplicando Estilos con Styled Components

Instalamos Styled Components:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
npm install styled-components
npm install styled-components
npm install styled-components

Modificamos HomeScreen.js para usar estilos:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
import styled from 'styled-components/native';
const Container = styled.View`
flex: 1;
padding: 20px;
background-color: #f8f9fa;
`;
const TaskInput = styled.TextInput`
border-bottom-width: 1px;
margin-bottom: 10px;
padding: 5px;
`;
const TaskText = styled.Text`
font-size: 18px;
color: #333;
`;
import styled from 'styled-components/native'; const Container = styled.View` flex: 1; padding: 20px; background-color: #f8f9fa; `; const TaskInput = styled.TextInput` border-bottom-width: 1px; margin-bottom: 10px; padding: 5px; `; const TaskText = styled.Text` font-size: 18px; color: #333; `;
import styled from 'styled-components/native';

const Container = styled.View`
  flex: 1;
  padding: 20px;
  background-color: #f8f9fa;
`;

const TaskInput = styled.TextInput`
  border-bottom-width: 1px;
  margin-bottom: 10px;
  padding: 5px;
`;

const TaskText = styled.Text`
  font-size: 18px;
  color: #333;
`;

Dentro del return:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<Container>
<TaskInput
placeholder="Nueva tarea"
value={task}
onChangeText={setTask}
/>
<Button title="Agregar" onPress={handleAddTask} />
<FlatList
data={tasks}
keyExtractor={(item) => item.id.toString()}
renderItem={({ item }) => (
<TouchableOpacity onPress={() => deleteTask(item.id, setTasks)}>
<TaskText>{item.text} ❌</TaskText>
</TouchableOpacity>
)}
/>
</Container>
<Container> <TaskInput placeholder="Nueva tarea" value={task} onChangeText={setTask} /> <Button title="Agregar" onPress={handleAddTask} /> <FlatList data={tasks} keyExtractor={(item) => item.id.toString()} renderItem={({ item }) => ( <TouchableOpacity onPress={() => deleteTask(item.id, setTasks)}> <TaskText>{item.text} ❌</TaskText> </TouchableOpacity> )} /> </Container>
<Container>
  <TaskInput
    placeholder="Nueva tarea"
    value={task}
    onChangeText={setTask}
  />
  <Button title="Agregar" onPress={handleAddTask} />
  <FlatList
    data={tasks}
    keyExtractor={(item) => item.id.toString()}
    renderItem={({ item }) => (
      <TouchableOpacity onPress={() => deleteTask(item.id, setTasks)}>
        <TaskText>{item.text} ❌</TaskText>
      </TouchableOpacity>
    )}
  />
</Container>

4. Probar la Aplicación

Ejecuta:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
npx expo start
npx expo start
npx expo start

Verifica que las tareas se guardan y eliminan correctamente.

0

Deja un comentario