【问题标题】:Unable to insert data to array in firebase firestore using react无法使用 React 将数据插入到 Firebase Firestore 中的数组
【发布时间】:2021-03-04 19:58:21
【问题描述】:

这是我第一次使用带有 react 的 firebase,我正在尝试制作一个应用程序,用户可以在其中将歌曲插入到 firebase firestore 的私人播放列表中:

这就是我存储创建用户的方式:

firebase.js

const app = firebase;
export const auth = app.auth();
export default app;

export const storage = firebase.storage();
export const db = firebase.firestore();
export const userCollection = db.collection('users');


export const CreateUser = async (email,password,username)=>{
  const authResult = await auth.createUserWithEmailAndPassword(email,password);
  userCollection.doc(authResult.user.uid)
    .set({
      created:firebase.firestore.FieldValue.serverTimestamp(),
      Email:email,
      userName:username,
      Playlist:[],
    });
} 
export const insertSong = async (song , email ) =>{
  await userCollection.where('Email' , '==' , email)
    .get()
    .then(snapshot=>{
      snapshot.forEach(snap=>{
        //if I console.log(snap.data()) my data is correct 
        snap.data().Playlist = [...snap.data().Playlist,song];
      })
    })
    .catch(err=>{
      console.log(err);
    })
}

在创建用户的地方我也设置了一个空的播放列表数组

现在在另一个组件中,我尝试更新特定用户的播放列表

上传.js

import {React , useState} from 'react';
import {insertSong, storage} from '../firebase';
import {useAuth} from './UserContext';

export default function Upload(){
  const {user} = useAuth(); //this is how I access the email of the user 
  const [disabled , setDisabled] = useState(false); 
  const [url , setUrl ] = useState(null);


  const checkSong = async (e)=>{ 
    const song = e.target.files[0];
    if(song){
      try{
        const songsRef = storage.ref('songs').child(song.name);
        setDisabled(true);
        await songsRef.put(song);
        console.log('Song has been inserted');
        const result = await songsRef.getDownloadURL();
        setUrl(result);  
        //if I do console.log(disabled) in this line it is false not true !
        insertSong(url,user.email); //this is where the problem happens 
      }catch(err){
        console.log(err);
      }
      setDisabled(false);
    } 
    
  }
  return (
    <div>
      <h1> Upload a song : </h1>
      <input type = "file" accept="audio/mp3,audio/*;capture=microphone" disabled = {disabled} onChange={checkSong}/>
    </div>
  );
  
}

所以当我在 firebase 网站上查看用户的播放列表时,它是空的。我认为这里的异步性存在问题,因为我的 disabled 变量在我尝试在用户的播放列表中插入歌曲之前变为假,正如我上面评论的那样。 非常感谢您的帮助。

【问题讨论】:

  • 代码在 getDownloadURL 部分之前是否正常工作?你得到结果网址了吗?
  • @p2hari 是的
  • 哦,现在我开始研究代码了。在快照中,您正在更改播放列表,但不会将其保存在 Firestore 中。您需要更新数据。

标签: reactjs firebase google-cloud-firestore firebase-storage


【解决方案1】:

在insertsong里面试试这个

try{ 
var snapshot = await userCollection.where('Email' , '==' , email);

if(!snapshot.empty){
var docsnap = snapshot.docs[0];
    var playlist = docsnap.data().Playlist;
    //if I console.log(snap.data()) my data is correct 
         playlist = [...song];

   docsnap.ref.update({"Playlist": playlist});
  }
} 


catch { (err)=>{
  console.log(err);
}};

【讨论】:

  • 它没有用,但我找到了解决方案。非常感谢您的宝贵时间 。检查我做了什么
【解决方案2】:

我创建了一个新方法来通过获取 doc id 作为输入并更新文档来更新播放列表数组

const updateArray = async (id,song)=>{  
  const document =  userCollection.doc(id);
  await document.update({
    Playlist: firebase.firestore.FieldValue.arrayUnion(song)
  }).catch(err=>{
    console.log(err);
  })
        
}

export const insertSong = async (song , email ) =>{
  await userCollection.where('Email' , '==' , email)
    .get()
    .then(snapshot=>{
      snapshot.forEach(snap=>{
        updateArray(snap.id,song)
      })
    })
    .catch(err=>{
      console.log(err);
    })
}

唯一的问题是,如果播放列表为空,它会先添加一个空元素,然后才能完美运行。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-18
    • 2017-10-08
    • 2021-02-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多