Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to save data locally using AsyncStorage in React Native.
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); } }
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using a non-existent method like 'storeItem' or 'saveItem'.
✗ Incorrect
The correct method to save data locally with AsyncStorage is setItem.
2fill in blank
mediumComplete the code to read data locally using AsyncStorage in React Native.
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); } }
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using methods like 'fetchItem' which do not exist in AsyncStorage.
✗ Incorrect
The correct method to read data locally with AsyncStorage is getItem.
3fill in blank
hardFix the error in the code to correctly check if local data exists.
React Native
async function checkData() {
const data = await AsyncStorage.getItem('key');
if (data [1] null) {
console.log('Data exists');
} else {
console.log('No data');
}
} Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using '==' which checks for equality instead of inequality.
✗ Incorrect
To check if data exists, we verify it is not equal to null using !=.
4fill in blank
hardFill both blanks to create a local data object and save it as a JSON string.
React Native
const user = {name: 'Alice', age: 30};
const jsonString = JSON.[1](user);
await AsyncStorage.[2]('user', jsonString); Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using JSON.parse instead of stringify.
Using getItem instead of setItem to save.
✗ Incorrect
Use JSON.stringify to convert the object to a string, then setItem to save it.
5fill in blank
hardFill all three blanks to read local JSON data and convert it back to an object.
React Native
const jsonString = await AsyncStorage.[1]('user'); if (jsonString !== null) { const user = JSON.[2](jsonString); console.log(user.[3]); }
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using setItem instead of getItem to read data.
Using stringify instead of parse to convert string.
✗ Incorrect
Use getItem to read, JSON.parse to convert string to object, then access name property.