0

I'm doing a react native app to manage notes and tasks.

I have two tables for each one. The problem is: I can save and display the notes without any problem. I try to do the same with the tasks. The task are created, displayed on the component, but when I reload or cloese the app, the task is gone.

The components are pretty the same. with some additions for the tasks.

These are my components:

-To create a task:

import React, { useState } from 'react';
import { ScrollView, StyleSheet, Text, View, TextInput, Pressable } from 'react-native';
import Icon from "react-native-vector-icons/Ionicons";
import { useDataContext } from '../dataProviders/DataProvider';
import { db } from '../database/database';

export default function CreateTasks() {
    const { handleAddTask } = useDataContext();

    const [taskTitle, setTaskTitle] = useState('');
    const [taskDate, setTaskDate] = useState('');
    const [taskTime, setTaskTime] = useState('');
    const [taskDescription, setTaskDescription] = useState('');

    const addTask = () => {
        const newValue = {
            taskTitle: taskTitle,
            date: taskDate,
            time: taskTime,
            taskDescription: taskDescription,
        };
        setTaskTitle(newValue.taskTitle);
        setTaskDate(newValue.date);
        setTaskTime(newValue.time);
        setTaskDescription(newValue.taskDescription);
        db.transaction(
            (tx) => {
                tx.executeSql(
                    'insert into tasks ( title, date, time, description) values(?, ?, ?, ?)',
                    [newValue.taskTitle, newValue.date, newValue.time, newValue.taskDescription]
                );
            },
        );
        handleAddTask(newValue);
        setTaskTitle(''); // Clear the input fields
        setTaskDate('');
        setTaskTime('');
        setTaskDescription('');
    };

    return (
        <View style={styles.container}>
           <ScrollView style={styles.inputArea}>
                <TextInput
                    style={styles.inputTitle}
                    value={taskTitle}
                    onChangeText={taskTitle => setTaskTitle(taskTitle)}
                    placeholder='Task'
                />
                <TextInput
                    style={styles.inputDate}
                    value={taskDate}
                    onChangeText={date => setTaskDate(date)}
                    keyboardType='default'
                    placeholder='xx/xx/xxxx'
                />
                <TextInput
                    style={styles.inputTime}
                    value={taskTime}
                    onChangeText={time => setTaskTime(time)}
                    keyboardType='default'
                    placeholder='00:00'
                />
                <TextInput
                    style={styles.input}
                    value={taskDescription}
                    onChangeText={taskDescription => setTaskDescription(taskDescription)}
                    multiline={true}
                    keyboardType='default'
                    placeholder='Description...'
                />
            </ScrollView>
            <View style={styles.buttonContainer}>
                <Pressable onPress={() => addTask()}>
                    <Icon
                        name={"bookmark"}
                        //color="#87CEFA"
                        size={40}
                    />
                </Pressable>
            </View> 
        </View>  
    )
}

-To display the tasks:

import React, { useState, useEffect } from 'react';
import { ScrollView, StyleSheet, Text, View, TextInput, Pressable, Alert } from 'react-native';
import TaskContainer from './TaskContainer';
import EditTasks from './EditTasks';
import { useDataContext } from '../dataProviders/DataProvider';
import { getTasks, insertIntoDeletedTasks, removeTask } from '../database/database';
import { Provider } from 'react-native-paper';
import Icon from "react-native-vector-icons/Ionicons";

export default function Tasks() {
  const { taskItems, setTaskItems } = useDataContext();

  useEffect(() => {
    (async () => {
      try {
        const fetchedTasks = await getTasks();
        setTaskItems(fetchedTasks);
      } catch (error) {
        console.error('Error fetching notes:', error);
        Alert.alert('Error fetching tasks. Please try again.');
      }
    })();
  }, []);

  const [searchQuery, setSearchQuery] = useState('');
    
  const regex = new RegExp(searchQuery, 'i');
  const filteredData = taskItems.filter(item =>
      regex.test(item.taskTitle)
  );

  const moveTaskToDeletedTasks = async (taskData) => {
    try {
      insertIntoDeletedTasks(taskData)
    } catch (error) {
      console.error('Error moving note to deletedNotes:', error);
      throw new Error('Error moving note to deletedNotes.');
    }
  };

  const deleteTask = (index) => {
    // Show a confirmation dialog
    Alert.alert(
      'Delete Task',
      'Are you sure you want to delete this task?',
      [
        {
          text: 'Cancel',
          style: 'cancel',
        },
        {
          text: 'Delete',
          style: 'destructive',
          onPress: () => {
            // If the user confirms, delete the task
            let deletedTask = taskItems[index];
            // Move the note to deletedNotes table
            moveTaskToDeletedTasks(deletedTask);

            // Remove the note from noteItems
            let itemsCopyTask = [...taskItems];
            itemsCopyTask.splice(index, 1);
            setTaskItems(itemsCopyTask);

            // Perform the actual deletion of the note from the Notes table
            removeTask(deletedTask);
          },
        },
      ],
      { cancelable: true }
    );
  }

  return (
    <Provider>
      <View style={styles.mainContainer}>
        <View style={styles.searchBox}>
          <TextInput
            placeholder="Search..."
            onChangeText={(text) => setSearchQuery(text)}
            value={searchQuery}
            style={styles.input}
          />
          <Icon
            name="search-outline"
            size={40}
          />
        </View>
        <ScrollView>
          <View style={styles.container}>
            {filteredData.map((item, index) => (
              item && item.taskTitle ? ( // Check if 'item' exists and has a 'title' property
                <Pressable
                  key={index}
                  onPress={() => deleteTask(index)}
                >
                  <TaskContainer
                    taskTitle={item.taskTitle}
                    date={item.date}
                    time={item.time}
                    taskDescription={item.taskDescription}
                    index={index}
                    task={item}
                  />
                </Pressable>
              ) : null
            ))}
          </View>
        </ScrollView>
        <EditTasks />
      </View>
    </Provider>
  )
}

-The task container:

import React from 'react';
import { StyleSheet, Text, View, Pressable } from 'react-native';
import Icon from "react-native-vector-icons/Ionicons";
import { useDataContext } from '../dataProviders/DataProvider';


export default function TaskContainer(props) {

    const { showDialogTask } = useDataContext();
    const { task } = props;

    return (
        <View styles={styles.container}>
            <View style={styles.TaskContainer}>
                <View style={styles.box1}>
                    <View style={styles.box11}>
                        <Text style={styles.titleItem}>Task</Text>
                        <Text style={styles.text} ellipsizeMode="tail" numberOfLines={1}>{task.taskTitle}</Text>
                    </View>
                </View>
                <View style={styles.box2}>
                    <View style={styles.box22}>
                        <Text style={styles.titleItem}>Date</Text>
                        <Text style={styles.text}>{task.date}</Text>
                    </View>
                    <View style={styles.box22}>
                        <Text style={styles.titleItem}>Time</Text>
                        <Text style={styles.text}>{task.time}</Text>
                    </View>
                </View>
                <View style={styles.box3}>
                    <View>
                        <Text style={styles.text} ellipsizeMode="tail" numberOfLines={1}>{task.taskDescription}</Text>
                    </View>
                </View>
                <View style={styles.box4}>
                    <Pressable onPress={() => showDialogTask(task)}>
                        <Icon
                            name="create-outline"
                            size={40}
                        />
                    </Pressable>
                </View>
            </View>
        </View>
    );
}

Tried to debug with chatgpt. Nothing worked.

Thanks for any help or feedback!

9
  • Consider adding console.log("num tasks:", taskItems?.length); console.log("num filtered:", filteredData?.length); just before the return() in Tasks and see what it outputs when the data isn't displaying. Commented Dec 18, 2023 at 21:49
  • Your question details not complete, you saying not working, you haven't include any error message, just log what happen on insert part and the select query Commented Dec 19, 2023 at 8:50
  • @GregFenton I got the following log: LOG num tasks: 18 LOG num filtered: 18. I have some console.logs when adding the tasks or notes. At least in these logs I get that it was added. The issue must be on the Task component or on the TaskContainer, but I can't see a thing. :'( Commented Dec 19, 2023 at 16:28
  • Does it log the same count both when the UI renders the tasks and when it does not render the tasks? Maybe put a console.log("task item is:", item); just before the return in TaskContainer and see what is logged when the UI is not rendering the tasks. Commented Dec 19, 2023 at 22:13
  • @GregFenton I rendered the app without adding a new task. When it renders, it doesn't display the logs. It happens just when I go to the Task tab. When I go to the Task tab for the first time, i get this: LOG num tasks: 0 LOG num filtered: 0 LOG num tasks: 19 LOG num filtered: 19. When I add a task, it logs: LOG num tasks: 20 LOG num filtered: 20 LOG task item is: undefined. When I close, reopen and go to the Task tab, it logs: LOG num tasks: 0 LOG num filtered: 0 LOG num tasks: 20 LOG num filtered: 20. Commented Dec 20, 2023 at 18:54

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.