Reputation: 384
i am new to react and firebase.
PROBLEM:
I am trying to access a variable which returns true when it successfully gets the result, it is working inside .then method, but outside then method cannot get the result (isStudent variable). I any suggestions, hints would be helpful.
const Routes = props => {
if (props.user) {
let isStudent=false;
const uid = props.user.uid;
firebase
.database()
.ref(`student/${uid}`)
.once("value")
.then(snapshot => {
if (snapshot.val().role === "student") {
console.log(snapshot.val());
isStudent=true
}
});
console.log(isStudent); //false
//i am getting the default value, if i remove that i get undefined
return (
<MainLayout>
<Switch>
<StudentPublicRoute
{...props}
exact
restricted={true}
path="/student/login"
component={StudentLogin}
/>
{isStudent&& <StudentPrivateRoute
{...props}
path="/student/studentdashboard"
exact
component={StudentDash}
/>}
</Switch>
</MainLayout>
Upvotes: 0
Views: 228
Reputation: 76
The method once
returns a Promise which means that your function will run asynchronous, so the function console.log
runs before you get the response from firebase.
In your case you will need to keep the value of isStudent in the React State.
The result will be something like this:
class YourComponent extends React.Component {
constructor(props) {
super(props);
this.state = {isStudent: false};
}
...
firebase
.database()
.ref(`student/${uid}`)
.once("value")
.then(snapshot => {
if (snapshot.val().role === "student") {
this.setState({
isStudent: true
});
}
}
Upvotes: 2
Reputation: 661
This is because console.log(isStudent) executes before isStudent=true.
This will always be the case since the call to firebase takes some time. Consider also using a class component rather than a function component and use some framework like redux/saga or redux/thump for asynchronous calls like this.
Maybe you could try with await/async, it may work.
Your code, as is, will never work.
Upvotes: 0