【发布时间】: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