I'm training on react-native. I'm trying to figure out how I can save data locally.
I have a to-do list and choose the person assigned to this task.
I would like to save the tasks that I add so that they are kept when I stop and restart the application for example. I was thinking of using async storage so I did it like this:
const storeData = async (task) => { try { await AsyncStorage.setItem('key', task) } catch (e) { // lance une erreur } }
But it doesn't seem to be working.
Here is all of my code for this page. Could you please help me get my code working, and explain to me the behavior of the function in the process?
Thank you.
import React, {useState} from 'react';
import { KeyboardAvoidingView, Text, View, TextInput, TouchableOpacity, Keyboard, ScrollView } from 'react-native';
import Task from '../../Task';
import SelectDropdown from 'react-native-select-dropdown'
import styles from "../../../assets/styles"
export default function Trucs() {
const [task, setTask] = useState();
const [taskItems, setTaskItems] = useState([]);
const users = ["Jibé", "Charly"]
const handleAddTask = () => {
Keyboard.dismiss();
setTaskItems([...taskItems, task])
setTask(null);
}
const storeData = async (task) => {
try {
await AsyncStorage.setItem('key', task)
} catch (e) {
// lance une erreur
}
}
const completeTask = (index) => {
let itemsCopy = [...taskItems];
itemsCopy.splice(index, 1);
setTaskItems(itemsCopy)
storeData(task)
}
return (
<View style={styles.wrap}>
{/* Added this scroll view to enable scrolling when list gets longer than the page */}
<ScrollView
contentContainerStyle={{
flexGrow: 1
}}
keyboardShouldPersistTaps='handled'
>
{/* Today's Tasks */}
<View style={styles.tasksWrapper}>
<Text style={styles.sectionTitle}>Trucs à faire</Text>
{/* This is where the tasks will go! */}
{
taskItems.map((item, index) => {
return (
<TouchableOpacity key={index} onPress={() => completeTask(index)}>
<View>
<Task text={item}/>
<SelectDropdown
data={users}
onSelect={(selectedItem, index) => {
console.log(selectedItem, index)
}}
buttonTextAfterSelection={(selectedItem, index) => {
// text represented after item is selected
// if data array is an array of objects then return selectedItem.property to render after item is selected
return selectedItem
}}
rowTextForSelection={(item, index) => {
// text represented for each item in dropdown
// if data array is an array of objects then return item.property to represent item in dropdown
return item
}}/>
</View>
</TouchableOpacity>
)
})
}
</View>
</ScrollView>
{/* Write a task */}
{/* Uses a keyboard avoiding view which ensures the keyboard does not cover the items on screen */}
<KeyboardAvoidingView
// behavior={Platform.OS === "ios" ? "padding" : "height"}
style={styles.writeTaskWrapper}
>
<TextInput style={styles.input} placeholder={'Rajouter un truc à faire'} value={task} onChangeText={text => setTask(text)} />
<TouchableOpacity onPress={() => handleAddTask()}>
<View style={styles.addWrapper}>
<Text style={styles.addText}> </Text>
</View>
</TouchableOpacity>
</KeyboardAvoidingView>
</View>
);
}
CodePudding user response:
I feel like you are not getting the Data that you have stored in the AsyncStorage properly. Look at my two Functions for storing and retrieving the data by the key.
const storeData = async (key, value) => {
try {
await AsyncStorage.setItem(key, value);
} catch (error) {
console.log(error);
}
};
const getData = async (key) => {
try {
const data = await AsyncStorage.getItem(key);
if (data !== null) {
console.log(data);
return data;
}
} catch (error) {
console.log(error);
}
};
You can then call getData("yourKey") wherever you want to get the stored elements.
CodePudding user response:
There are a couple of points here:
1- AsyncStorage.setItem() takes a key and a value that are both STRINGS. so you need to do await AsyncStorage.setItem('key', JSON.stringify(task))
in your storeData method
2- You need to READ the data once the component mounts and put it inside of your state using something like useEffect for it to be shown once you restart your app. For example:
useEffect(() => {
AsyncStorage.getItem('key').then((res) => {
setTask(JSON.parse(res));
})
} , [])