App crashes when trying to save something into asyncStorage. It crashes without an error message however I think the problem is in the while loop:
JavaScript
x
36
36
1
const saving = () => {
2
console.log("ran") // gets called
3
let loop = true
4
let cont = 0
5
while (loop == true) {
6
console.log("got here") // Doesn't even get called
7
AsyncStorage.getItem(`Item-${cont}`, (error, result) => {
8
console.log("here")
9
if (error) {
10
Toast.show({
11
type: 'error',
12
text1: 'An error has ocurred!'
13
})
14
loop = false
15
} else if (result == null) {
16
AsyncStorage.setItem(`Item-${cont}`, (error) => {
17
console.log("there")
18
if (error) {
19
Toast.show({
20
type: 'error',
21
text1: 'Error occurred while saving workout!'
22
})
23
loop = false
24
} else {
25
Toast.show({
26
type: 'success',
27
text1: 'Workout saved successfully!'
28
})
29
loop = false
30
}
31
})
32
}
33
})
34
cont++
35
}
36
As soon as the loop gets executed, the app crashes, console.log("got here")
doesn’t even run.
This function is called from a Pressable component:
JavaScript
1
6
1
<Pressable
2
onPress={() => saving()}
3
>
4
5
</Pressable>
6
Advertisement
Answer
I had to change it from a while loop to a for loop, what I did was the following:
JavaScript
1
42
42
1
for (let i = 0; i < cont; i++) {
2
await AsyncStorage.getItem(`Workouts-${i}`, (error, result) => {
3
if (error) {
4
Toast.show({
5
type: 'error',
6
text1: 'ERROR',
7
text2: 'An error has ocurred!'
8
})
9
cont = 0
10
} else if (result == null) {
11
var object = {
12
name: rec_workoutName,
13
exercises: rec_renderedArray,
14
difficulty: rec_workoutDifficulty,
15
}
16
AsyncStorage.setItem(`Workouts-${i}`, JSON.stringify(object), (error) => {
17
console.log("saved")
18
if (error) {
19
Toast.show({
20
visibilityTime: 2000,
21
type: 'error',
22
text1: 'ERROR',
23
text2: 'An error has ocurred!'
24
})
25
cont = 0
26
} else {
27
Toast.show({
28
visibilityTime: 2000,
29
type: 'success',
30
text1: 'SUCCESS',
31
text2: 'Workout saved successfully!'
32
})
33
cont = 0
34
}
35
})
36
}
37
})
38
39
40
cont++
41
}
42
I hope this helps someone who encounters the same issue.