1
I have an error saving checkbox status with Asyncstorage. When exiting/reloading the screen, the first checkbox is always marked and the other’s markings are removed https://imgur.com/bFxof0q
I need the checked boxes to be saved in Asyncstorage and when reloading the app, the boxes that were marked earlier are loaded and shown to the user, I am not able to find the solution. My code is like this:
import React, { useState, useEffect } from 'react';
import AsyncStorage from '@react-native-community/async-storage';
import { View, CheckBox } from 'react-native';
import { Ionicons } from '@expo/vector-icons';
import * as Animatable from 'react-native-animatable';
//styles
import { Container, Text, DeleteItem } from './styles';
function TaskList({ data, handleDelete }) {
const [isSelected, setSelection] = useState(false);
//buscando todas as caixas ao iniciar o app
useEffect(() => {
async function loadBox() {
const boxStorage = await AsyncStorage.getItem('@checkBox');
if (boxStorage !== null) {
setSelection(JSON.parse(boxStorage));
}
}
loadBox();
}, []);
//salva caso tenha alguma caixa alterada
useEffect(() => {
async function saveBox() {
await AsyncStorage.setItem('@checkBox', JSON.stringify(isSelected));
}
saveBox();
}, [isSelected]);
return (
<Animatable.View useNativeDriver animation="bounceIn">
<Container>
<View>
<CheckBox value={isSelected} onValueChange={setSelection} />
<Text>{data.task}</Text>
</View>
<DeleteItem onPress={() => handleDelete(data)}>
<Ionicons name="ios-trash" size={30} color="#FA6C30" />
</DeleteItem>
</Container>
</Animatable.View>
);
}
export default TaskList;
Could you show me how? I’m a little confused in this part here. I appreciate it. The code is in: https://github.com/PlayerNumber2/app-tasking
– player 2
First you need to make clear in your question, what action you want to do when checking, in your question it was not very clear what you intend to do, second, I noticed that you created two useEffect, that in practice we know that this is wrong in React, hook Effect, you are rewriting useEffect function.
– Ivan Ferrer
I edited the question... I need the checked boxes to be saved in Asyncstorage and when reloading the app, the boxes that were marked earlier will be loaded and shown to the user. I didn’t know that two useEffect is wrong, obg!
– player 2
It’s okay to use 2
useEffects
. The problem there is that you are saving in Asyncstorage always as@checkBox
, you need aid
for each one to be able to save and recover right. Or even save the direct list instead of a record for each checkbox, for example:[{ "id1": "true", "id2": "false" }]
.– Rafael Tavares