Reputation: 3320
I'm trying to useEffect when my component first loads. UseEffect has a call to a firebase function but it's returning null and I can't figure out why.
const [emails, setEmails] = useState({
reports: [],
savedReports: [],
})
useEffect(() => {
props.firebase.getEmailReportsTo(props.orgId)
.once('value')
.then(returnedEmails => {
console.log(returnedEmails.val());
setEmails(prevEmails => ({
...prevEmails,
savedReports: [returnedEmails.val()]
}))
})
}, []);
Here I make a call to a firebase method which returns the values. I've confirmed there's values in that endpoint. The above returns null. It appears as if the console log is logging BEFORE the call finishes executing. However I'm not sure why since console.log is in then
. Console.log isn't the important part but then it creates null under my state also.
When I do this:
useEffect(() => {
props.firebase.getEmailReportsTo(props.orgId)
.once('value')
.then(returnedEmails => {
console.log(returnedEmails.val());
setEmails(prevEmails => ({
...prevEmails,
savedReports: [returnedEmails.val()]
}))
})
}, [emails.savedReports]);
I can view the console.log with the data but this kicks into an infinite loop.
Changing [emails.savedReports]
to [emails]
also returns null
This can be broken down into two question but whatever helps me achieve the result of setting the state to the firebase call works for me. One would be why is the useEffect not waiting for then to complete? The other would be if [emails.savedReports is updated then shouldn't it stop executing useEffect? However I can resolve this is cool with me.
Upvotes: 1
Views: 1235
Reputation: 2605
You are making request when you are getting your props.orgId
useEffect(() => {
if(props.orgId){ // if you receive your orgId then an then your request will be call
props.firebase.getEmailReportsTo(props.orgId)
.once('value')
.then(returnedEmails => {
console.log(returnedEmails.val());
setEmails(prevEmails => ({
...prevEmails,
savedReports: [returnedEmails.val()]
}))
})
}
}, [props.orgId]);
Upvotes: 2