mercredi 7 septembre 2022

ToDo Async app toggle complete/not complete not staying saved in async storage using hooks

It has been days of me on this error. I am relatively new to stackoverflow so my apologies if my question isn't clear or I am not asking it in the correct format. I am trying to create a to do app in react native that is using async storage. I created a toggle button that saves the toggle to a state

[checkboxChecked, setCheckboxChecked=useState(false)

 const toggleComplete = () => {

        setCheckBoxState(!checkBoxState)
        handleEdit();
        console.log(checkBoxState)

    }

When the user checks on it - seems to be showing up correctly as marked true and false in the console. Then, this is passed to an edit handler to update the array, again console shows it is the correct state:

  const handleEdit = () => {
        props.editHandler(props.todoKey, text, checkBoxState);
        console.log(text2, checkBoxState)
    };

Then it shows that it saved correctly:

 const [todos, setTodos] = React.useState([]);
 const handleEdit = (todoKey, text, newStatus) => {
        const newTodos = [...todos];
        const index = newTodos.findIndex(todos => todos.key === todoKey);
        newTodos[index] = Object.assign(newTodos[index], {title: text, status: newStatus});
        setTodos(newTodos);
    
        console.log(todos, newStatus)
    };

The async function to save to the device and load are as follows: To save:

const saveTodoToUserDevice = async (todos) => {
        try {
            const stringifyTodos = JSON.stringify(todos);
            await AsyncStorage.setItem('todos', stringifyTodos);
        } catch (error) {
            console.log(error);
        }
    };

To load from the device:

const getTodosFromUserDevice = async () => {
        try {
            const todos = await AsyncStorage.getItem('todos');
            if (todos != null) {
                setTodos(JSON.parse(todos));
                console.log("loaded successfully");
            }
        } catch (error) {
            console.log(error);
        }
    };

So here is the issue - I get the console log that says it is saved correctly and loaded. BUT, when I refresh, the checkbox state is not saved at all, just the title text (so it is saving but the checkbox would always be false (the initial state set). If I clicked on true, it would show as true and then when I refresh, it goes back to false.

I have spent days and days on this and can't figure it out. Any direction would be helpful Thank you!




Aucun commentaire:

Enregistrer un commentaire