Complete the code to save data locally using AsyncStorage in React Native.
import AsyncStorage from '@react-native-async-storage/async-storage'; async function saveData(value) { try { await AsyncStorage.[1]('key', value); } catch (e) { console.error(e); } }
The correct method to save data locally with AsyncStorage is setItem.
Complete the code to read data locally using AsyncStorage in React Native.
import AsyncStorage from '@react-native-async-storage/async-storage'; async function readData() { try { const value = await AsyncStorage.[1]('key'); if(value !== null) { return value; } } catch(e) { console.error(e); } }
The correct method to read data locally with AsyncStorage is getItem.
Fix the error in the code to correctly check if local data exists.
async function checkData() {
const data = await AsyncStorage.getItem('key');
if (data [1] null) {
console.log('Data exists');
} else {
console.log('No data');
}
}To check if data exists, we verify it is not equal to null using !=.
Fill both blanks to create a local data object and save it as a JSON string.
const user = {name: 'Alice', age: 30};
const jsonString = JSON.[1](user);
await AsyncStorage.[2]('user', jsonString);Use JSON.stringify to convert the object to a string, then setItem to save it.
Fill all three blanks to read local JSON data and convert it back to an object.
const jsonString = await AsyncStorage.[1]('user'); if (jsonString !== null) { const user = JSON.[2](jsonString); console.log(user.[3]); }
Use getItem to read, JSON.parse to convert string to object, then access name property.
