Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

150
Visualizações
AsyncStorage setItem inside loop crashes

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:

const saving = () => {
console.log("ran") // gets called
let loop = true
               let cont = 0
               while (loop == true) {
                    console.log("got here") // Doesn't even get called
                    AsyncStorage.getItem(`Item-${cont}`, (error, result) => {
                         console.log("here")
                         if (error) {
                              Toast.show({
                                   type: 'error',
                                   text1: 'An error has ocurred!'
                              })
                              loop = false
                         } else if (result == null) {
                              AsyncStorage.setItem(`Item-${cont}`, (error) => {
                                   console.log("there")
                                   if (error) {
                                        Toast.show({
                                             type: 'error',
                                             text1: 'Error occurred while saving workout!'
                                        })
                                        loop = false
                                   } else {
                                        Toast.show({
                                             type: 'success',
                                             text1: 'Workout saved successfully!'
                                        })
                                        loop = false
                                   }
                              })
                         }
                    })
                    cont++
}

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:

<Pressable
   onPress={() => saving()}
>

</Pressable>
about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

So i don't really understand why you saving individual items, you could serialize an array and save it all at once, like that:

await AsyncStorage.setItem('data', JSON.stringify(data));

Also when you tried to call AsyncStorage.setItem, you have an key and a call back, but i don't see any values being set, so i think you have to do something like this:

await AsyncStorage.setItem(`Item-${cont}`, value, (error) => { /* callback */ });

I don't think its a good idea get items then immediately saves, you should get all the data at the start then save it at some point, and consider that localStorage it's not a database.

You also can check the documentation about AsyncStorage for reactNative here

about 4 years ago · Juan Pablo Isaza Relatório

0

I had to change it from a while loop to a for loop, what I did was the following:

for (let i = 0; i < cont; i++) {
                    await AsyncStorage.getItem(`Workouts-${i}`, (error, result) => {
                         if (error) {
                              Toast.show({
                                   type: 'error',
                                   text1: 'ERROR',
                                   text2: 'An error has ocurred!'
                              })
                              cont = 0
                         } else if (result == null) {
                              var object = {
                                   name: rec_workoutName,
                                   exercises: rec_renderedArray,
                                   difficulty: rec_workoutDifficulty,
                              }
                              AsyncStorage.setItem(`Workouts-${i}`, JSON.stringify(object), (error) => {
                                   console.log("saved")
                                   if (error) {
                                        Toast.show({
                                             visibilityTime: 2000,
                                             type: 'error',
                                             text1: 'ERROR',
                                             text2: 'An error has ocurred!'
                                        })
                                        cont = 0
                                   } else {
                                        Toast.show({
                                             visibilityTime: 2000,
                                             type: 'success',
                                             text1: 'SUCCESS',
                                             text2: 'Workout saved successfully!'
                                        })
                                        cont = 0
                                   }
                              })
                         }
                    })


                    cont++
               }

I hope this helps someone who encounters the same issue.

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda