【问题标题】:How to write to firebase for a specific user?如何为特定用户写入firebase?
【发布时间】:2020-12-05 05:02:22
【问题描述】:

我是 firebase 的超级新手,我正在查看 https://firebase.google.com/docs/auth 我能够使用firebase注册并登录,我将用户信息添加到身份验证->用户中。然后在您登录后重定向到一个表单。该表单当前将我想要的数据添加到实时数据库中(我在注册和登录之前让它工作)但我的问题是数据没有附加/在它登录的帐户下.所以现在只是一堆随机数据,不知道是谁的数据。我环顾四周,找不到任何有关如何使两者连接的信息。下面我包括了我的登录功能和更新数据库的功能。感谢您的帮助!

function loggingIn() {
  var notyf = new Notyf();
  console.log("Logging In");
  var email = document.getElementById("emailVal").value;
  var password = document.getElementById("passVal").value;
  console.log("Email: ", email, " Password: ", password);
  const promise = firebase.auth().signInWithEmailAndPassword(email, password);
  firebase.auth().onAuthStateChanged(function(user) {
    if (user) { // User is signed in.
      notyf.success('Logged in successfully');
      questionPage()
    } else {
      promise.catch(e => alert(e.message));
    }
  });
}

function setup(){
  //initialization and firebaseConfig is here as well
   dataMessage = firebase.database().ref('PersonData');
}
function writeUserData(activity, hours) {
  let newdataMessage = dataMessage.push();
  newdataMessage.set({
   funactivity: activity,
   sleep: hours
 });
}

我找到的解决方案如下:

function writeUserData(activity, hours) {
  var userId = firebase.auth().currentUser.uid;
  dataMessage = firebase.database().ref('PersonData/'+userId);
  let newdataMessage = dataMessage.push();
  newdataMessage.set({
   funactivity: activity,
   sleep: hours
   });
  }

使用 firebase.auth().currentUser.uid;让我将数据添加到当前用户。

【问题讨论】:

    标签: javascript firebase firebase-authentication


    【解决方案1】:

    您可以构建您的发布路线以获取动态数据,这是一个示例:

    let postMessageRef = firebase.database().ref(`messages/${path}`);
    

    在这种情况下,您可以动态地将路径更改为用户名/您的条件是什么

    然后这是实际的帖子

    postMessageRef
        .set({
            message: message,
            from: userName
        })
        .catch((err) => console.log(err))
    

    编辑 下次我会读得更好...

      let userName = "placeholderToPreventDBWipes";
    
      const onAuthStateChanged = (user) => {
        userName = user;
      };
    
    
     ~~In this case I used useEffect, but you can throw this in your .then()~~
          useEffect(() => {
            const subscriber = auth().onAuthStateChanged(onAuthStateChanged);
            return subscriber; //unsub @ unmount
          }, []);
    

    【讨论】:

    • 这是一个消息应用程序,所以我的路线是消息/无论如何,但您可以将其更改为对您的应用程序有意义的东西。路由是在嵌套在 .ref 括号内的引号内定义的。
    • 感谢您的回复。我有类似的东西,但我缺少来自:用户名,如何从我的身份验证用户“数据库”(或当前登录的用户)获取我的用户。感谢您的回答,一旦我了解如何让用户按用户分开,我就会看到它应该与我在上面使用 newdataMessage 时所做的相同。
    • 有几种不同的方法可以做到这一点,我建议使用 useContext。这是文档的链接:reactjs.org/docs/context.html
    • 如果我的问题对您有帮助,我非常感谢您将此标记为解决方案
    • 还有其他不使用react的方式吗?(不知道react)。你的回答有点帮助,但它没有回答我的问题:/对不起(你分享的代码是我已经拥有的)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-11
    • 1970-01-01
    • 2020-10-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多