0

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>,
Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
Manpreet Oberoi
  • 385
  • 3
  • 4
  • 13
  • and which component is that code from, and which function, and where is that function called, and what is the relevance of the first snippet of code? Please post a more complete code sample, also you used push wrongly – Dominic Sep 07 '16 at 09:39
  • its code from Loginpanel component. – Manpreet Oberoi Sep 07 '16 at 09:44
  • my browser is pointing the error towards this this.props.router.push('Index'); .... can you guide me why push is wrongly used and my code is on loginpanel page and and with this elseif i am trying to go to another component name as Index – Manpreet Oberoi Sep 07 '16 at 09:46
  • @DominicTobias Can you help me with this – Manpreet Oberoi Sep 07 '16 at 09:51

1 Answers1

0

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:

Community
  • 1
  • 1
Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807