React-Native Asyncstorage returna null

Asked

Viewed 349 times

0

Good I’m having a problem when I will save some data in Asyncstorage, when I will return it comes null.

salvage :

export const listarRecados = () => {
    return dispatch => {
        firebase.database().ref('/Recados/')
          .on('value', recados => {
              var recado = {};
              $.forEach(recados.val(), (recados, recID) => {
                    firebase.database().ref('/Equipe/').child(recados.enviadoPorId)
                    .once('value', equipe => {
                        enviadoPor = equipe.val()
                        recado[recID] = {...recados, recID, ...enviadoPor}
                    })
              })
              AsyncStorage.setItem('Recados', JSON.stringify(recado));
              dispatch({ type: LISTAR_RECADOS, payload: recado })
          })
     }
};

return:

AsyncStorage.getItem('Recados', (erro, resultado) => {
            console.log(">>>", resultado)
        });

it returns null

  • Apparently everything is correct, what happens when you re-export this code, keeps returning null ? According to the React Native documentation, getItem() returns null in callback when there is no value for that key

  • Peter, so for some reason the setItem not this salvage will be that there is something wrong because before it appeared normal now stopped after I added the team search.

1 answer

1


The problem is why firebase.database(). ref('/Team/'). Child is an asynchronous call. When you call Asyncstorage.setItem your message object has not yet been completed.

You need to ensure that the . Once was called before making the setItem. If it wasn’t inside a foreach, Asyncstorage.setItem could be inside the . Once, but in this case it will call again and again. To avoid this repeated call you can use the foreach index to only save to the last item. It would look like this:

export const listarRecados = () => {
return dispatch => {
    firebase.database().ref('/Recados/')
      .on('value', recados => {
          var recado = {};
          $.forEach(recados.val(), (recados, recID) => {
                firebase.database().ref('/Equipe/').child(recados.enviadoPorId)
                .once('value', equipe => {
                    enviadoPor = equipe.val()
                    recado[recID] = {...recados, recID, ...enviadoPor}
                    if(recID==recados.val().length){
                        AsyncStorage.setItem('Recados', JSON.stringify(recado));
                        dispatch({ type: LISTAR_RECADOS, payload: recado })
                     }
                })
          })
      })
 }

};

Browser other questions tagged

You are not signed in. Login or sign up in order to post.