I am working on my first React Native app. I am trying to learn how AsyncStorage works, but I somehow can't make it work even though it is said to be simple.
I am trying to save the data to storage, whenever the store is updated.
The problem is that the code below the line:
"await AsyncStorage.setItem("TODOS", jTodo)" does not seem to run. I don't know what the problem is...
const unsubscribe = store.subscribe(save);
async function save(){
try {
const todos = store.getState().todos
console.log(todos)
const jTodo = JSON.stringify(todos)
await AsyncStorage.setItem("TODOS", jTodo)
console.log("saving 2: " + todos);
} catch (e) {
console.error('Failed to save todos.' + todos)
}
}
The same is the case when I try to load data from storage. Again the code below the line: "const jTodos = await AsyncStorage.getItem('TODOS')" does not seem to run.
async function load() {
try {
console.log("so far even better")
const jTodos = await AsyncStorage.getItem('TODOS')
const todos = JSON.parse(jTodos);
console.log(todos);
todos.map((todo) => this.props.addTodo(todo))
} catch (e) {
console.error('Failed to load todos.')
}
}
load();
I hope some of you can point out what the problem is! Thank you in advance!!
If you are using android there is known issues with it not working.
"cold boot" your emulator from android studio.
https://github.com/facebook/react-native/issues/14101
Related
I'm trying to implement secure store (like async storage) into my testproject and it works. The only thing that doesn't work appears to be my load() useEffect that runs every time I start a new session.
So every time I start the session "null is not an object" appears and throws errors at every part where I'm looking for my list on my home-screen (my state is called goals).
but if I temporarily turn it off, add a goal to my list, and then turn it on - it works fine every time I restart the app
I feel like I need to write a condition in my load() statement but I can't figure out what, I think the app runs the load() and gets stuck at the statements where I use goals before I've added any. Can someone help me here? I've tried if (goals !== null) but it doesn't work.
const [goals, setGoals] = useState([])
const load = async() => {
if (goals !== null) {
try {
const goalsValue = await SecureStore.getItemAsync('Goals');
setGoals(JSON.parse(goalsValue))
} catch (err) {
alert(err)
}
}
}
useEffect(()=> {
load()
},[])
So what is happening is that there's nothing inside goalsValue so when you try parsing it you get an error. To avoid that you should add an if statement that checks if it's empty or not
const [goals, setGoals] = useState([])
const load = async() => {
if (goals !== null) {
try {
const goalsValue = await SecureStore.getItemAsync('Goals');
if(goalsValue) setGoals(JSON.parse(goalsValue))
}catch (err) {alert(err)}
}}
useEffect(()=> {
load()
},[])
Try this and let me know if it works ☺️
I want to store app data in AsyncStorage. And I want to persist that data and never get lost when app is going to refresh. Actually I'm going to create a job listing site and I want that user choose cities once whom jobs he wants to see and save that information forever.
I'm doing like this.
deviceStorageCity.saveItem("cities", checkedCities);
export const deviceStorageCity = {
async saveItem(key, value) {
try {
var jsonOfItem = await AsyncStorage.setItem(key, JSON.stringify(value));
return jsonOfItem;
} catch (error) {
console.log('AsyncStorage Error: ' + error.message);
}
}
};
But when I refresh state of that page is also refreshed.
Any help would be appriciated.
firstly I had tried with one Async-storage data , it was working. The problem went with other Async-storage data that I gave on other form. It was not working. Can any one help me with this issue?
Data:-
StoreImageData = async () => {
const Obj = "save"
test.push(Obj)
Alert.alert(JSON.stringify(test))
try {
await AsyncStorage.setItem('#Store', JSON.stringify(test))
this.props.navigation.navigate('CarView');
Alert.alert('Saved', 'Successful');
} catch (e) {
// saving error
}
}
I am using AsyncStorage.getItem in React Native.
As soon as the Application loads, I want to get the saved data in the device memory using AsyncStorage.getItem. I thought of using ComponentDidMount(). So as soon as the components are loaded, I want to run the AsyncStorage.getItem automatically and save the data to the array DATA. This way the user will not push any button to start rendering what is saved on the memory of the device.
I used the code below, but I do not see any console.log activity. But the console.log works on my other pages on same program here. It seems the ComponentDidMount() did not get executed.
Thanks!
componentDidMount(){
async () => {
try {
const HomeData = await AsyncStorage.getItem('#MyApp_Homekey')
return HomeData
} catch (e) {
console.log('There was error.')
}
if(!HomeData){
console.log('There are no Dimmer Light saved in the memory.')
}
else {
console.log('There is value in data after getItem.')
this.setState(DATA = HomeData)
}
}
As metioned in comment you should use async for componentDidMount as:-
componentDidMount = async () => {
const HomeData = await AsyncStorage.getItem('#MyApp_Homekey')
if(!HomeData){
console.log('There are no Dimmer Light saved in the memory.')
}
else {
console.log('There is value in data after getItem.')
this.setState(DATA = HomeData)
}
}
So my problem is what the title says, and I have been stuck on this problem for over a week now and am at a loss for what I can do. Here's the code
I've tried many different methods but none seem to work, at least with the saving of the file. Please let me know if you need to see more code.
async _stopRecordingAndEnablePlayback() {
this.setState({
isLoadingz: true
});
try {
await this.recording.stopAndUnloadAsync();
} catch (error) {
}
const info = await FileSystem.getInfoAsync(this.recording.getURI());
console.log(
`FILE INFO: ${JSON.stringify(info)}`,
info.uri
);
const arr = [];
const xFileInfo = JSON.stringify(info);
arr.push(xFileInfo);
this.setState({ fileInfo: arr, fileUri: info.uri });
console.log(arr);