2017-11-10 2 views
0

특정 사용자의 데이터를로드하고 특정 입력 필드로 푸시해야합니다.Firebase 및 Vue Js 라이프 사이클 후크

var query = db.ref('Clients/'+ clientName +'/form/'); 

다음과 같이 내가 mounted() 라이프 사이클 후크의 데이터를 fecth :

mounted(){ 

// Grab current user logged in from Firebase 
var user = firebaseApp.auth().currentUser; 

if (user){ 
// Grab displayName to use in path to retrieve that client's data 
var clientName = firebaseApp.auth().currentUser.displayName; 

// The path to that specific's client data 
var query = db.ref('Clients/'+ clientName+'/form/'); 

    query.once('value') 
    .then((snapshot) => { 

     // Get the client's location from Firebase and assign to clientLocation data in the DOM 
     this.clientLocation = snapshot.child('clientLocation').val(); 

    }); 
    } 

} 

내가 변경하고 데이터를 다시로드하지 않고 내 코드를 저장 제대로을 누르면됩니다 중포 기지의 경로에 위치 . 나는 모든 생명주기 후크 주위 재생

Error in mounted hook: "TypeError: Cannot read property 'displayName' of null" 

:

  1. beforeCreate
  2. beforeMount
  3. 을 만들어
  4. beforeUpdate
  5. 탑재 그러나 다시로드에 나는 다음과 같은 오류가 발생합니다
  6. 업데이트 됨
  7. beforeDestroy는

을 파괴하지만 데이터가 표시되지 않습니다. firebaseApp가 "로드 된"상태가 아니기 때문에 "displayName"속성 값을 가져올 수 없으므로 데이터 경로를 채울 수 없습니다.

작동하는 코드는 어떻게로드해야합니까? 너무 일찍 실행되는 것 같습니다.

답변

2

사용자 정보를 비동기 적으로로드하거나 새로 고쳐야 할 수 있습니다. 따라서 사용자가 사용 가능할 때 코드가 실행되도록 항상 an auth state listener을 사용하십시오. 링크 된 문서에서 수정 된 항목 :

firebase.auth().onAuthStateChanged(function(user) { 
    if (user) { 
    // Grab displayName to use in path to retrieve that client's data 
    var clientName = firebaseApp.auth().currentUser.displayName; 

    // The path to that specific's client data 
    var query = db.ref('Clients/'+ clientName+'/form/'); 

    var that = this; 
    query.once('value').then((snapshot) => { 
     // Get the client's location from Firebase and assign to clientLocation data in the DOM 
     that.clientLocation = snapshot.child('clientLocation').val(); 
    }); 
    } 
}); 

당신은 mounted()에 넣고 수 있지만, 그것은 또한 다른 라이프 사이클 방식으로 작동합니다.

+0

안녕하세요, Frank! 감사! 내가 마운트 오류가 없지만, 지금 얻을 : "잡히지 않는 (약속 있음) TypeError : undefined"clientLocation '속성을 설정할 수 없습니다. 나는 값과 올바른 콘솔을 기록했다. 어떤 아이디어? – Tony

+0

흠 .... 굵은 화살표를 사용하면 'this'가 동일하게 유지되어야합니다. 코드를 명시 적으로 캡처하도록 업데이트했습니다. –