React-Native AsyncStorage will return null

0

I'm having a problem when I save some data in AsyncStorage, when I go back it comes null.

save:

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

    
asked by anonymous 02.09.2017 / 05:39

1 answer

1

The problem happens because firebase.database (). ref ('/ Team /'). child is an asynchronous call. When you call AsyncStorage.setItem your message object has not yet been populated.

You need to ensure that the .once was called before making the setItem. If it were not inside a forEach, the AsyncStorage.setItem could be inside .once, but in that case it will call repeatedly. To avoid this repeated call you can use the index of the forEach to save only the last item. I would stay + - 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 })
                     }
                })
          })
      })
 }

};

    
14.09.2017 / 13:49