firebase :: Cannot read property 'props' of null

Hello i am trying to use react-router with firebase. but it gives me this error.

Cannot read property ‘props’ of null

this is exactly code, where i am using my react-router

Down code is on component as loginpanel component.

else if (this.email.value === currentObject.username && this.password.value === currentObject.password && user_id)
 {
     var data25 = '';
     var groupid = '';

     var query = firebase.database().ref("/Users_group").orderByChild('id').equalTo(user_id);
     query.on("child_added", function hello (snapshot) {

         data25 = snapshot.val();

         groupid = data25.User_Group_id;

         AppActions.createComment(currentObject.username, currentObject.password, user_id, groupid);

//error is here,

         this.props.router.push('Index');
     },()=>{

     });

 }

my react router is declared on main.jsx
my react-router looks like this.

       <Router history={hashHistory}>
      <Route path="/" component={Loginpanel}/>
      <Route path="Index" component={Index}/>
      <Route path="Form" component={Form} />
      <Route path="Checkindex" component={Index}/>
      <Route path="Signup" component={Signup}/>
      <Route path="Admin" component={Admin}/>
      <Route path="AdminEditDetails" component={AdminEditDetails}/>
      <Route path="AdminDetails" component={AdminDetails}/>

     </Router>,

Here is Solutions:

We have many solutions to this problem, But we recommend you to use the first solution because it is tested & true solution that will 100% work for you.

Solution 1

In your callback, the this pointer no longer points to your React component. There are many ways to deal with this:

Capture this into another variable

var component = this;
query.on("child_added", function hello (snapshot) {
    ...
    component.props.router.push('Index');
});

Explicitly bind this

query.on("child_added", function hello (snapshot) {
    ...
    this.props.router.push('Index');
}).bind(this);

Use fat arrows, which implicitly keeps this

query.on("child_added", snapshot => {
    ...
    this.props.router.push('Index');
});

Note that this is a very common problem that developers have in JavaScript and I highly recommend you learn more about the way this behaves with callbacks:

Note: Use and implement solution 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply