Reputation: 970
I have my login on my navbar component but i have something on my main component that i need to update when someone logs in, i can get the login on the navbar to work but the variable isn't being passed back up to the parent my code that calls the navbar looks like this
<LoginBar AuthRes={this.state.AuthResults} IsLoggedIn={this.state.isLoggedIn}/>
this is passing the variable IsLoggedIn into my navbar and then in my navbar my code is this
LoginAuth = (Res) => {
if (Res.username === this.state.Username && Res.password === this.state.Password) {
this.setState({
IsLoggedIn: true,
}, function(){
});
this.hideModal();
} else {
console.log("Gets to login auth and false");
}
}
CheckLoginAuth() {
console.log("gets to check login auth");
console.log(this.state.AuthRes);
console.log("Username=" + this.state.Username);
console.log("Password=" + this.state.Password);
var self = this;
this.props.AuthRes.map(function (Res) {
console.log("ID=" + Res.id);
console.log("Username=" + Res.username);
console.log("Password=" + Res.password);
self.LoginAuth(Res);
});
}
so on clicking login it will ask you for the details it will then use .map to go through all the login details in the file i have, then it passes that into LoginAuth which will check that the input matches the auth file and sets IsLoggedIn to true if it matches how would i push IsLoggedIn back to the parent to change something on there
also how would i break the loop once i found the correct one as if i have an alert saying alert("Incorrect username or password")
is does this 3 times if all three values haven't been met
thanks Andy
edit:
When i do this.props.IsLoggedIn(true) or this.props.isLoggedIn(true) i get the error TypeError: Cannot read property 'props' of undefined so it saying isLoggedIn and IsLoggedIn are undefined yet
state = {
AuthRes: this.props.AuthRes,
isOpen: false,
Username: '',
Password: '',
searchResults: [],
testMode: true,
isLoggedIn: this.props.IsLoggedIn,
Auth: '',
}
Upvotes: 0
Views: 2936
Reputation: 88
What you can do is pass a function from the Parent component to the Child component using props. Lets say you have this function in your parent component:
function doSomething(argument){
console.log(argument);
}
Now pass this function to your child component:
<LoginBar AuthRes={this.state.AuthResults} IsLoggedIn={this.state.isLoggedIn} doSomething={this.doSomething}/>
Then, in child component, when you get that function, just call it from wherever you need:
//Some code ...
this.props.doSomething(argument)
//Some code ...
For the break question, you can't break map
function. What you could do is convert you map
function to for
loop and use break
or use some flag in map to know when to stop execution of the map. Check this out https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/break
Upvotes: 1