Reputation: 425
I'm stuck with a problem passing callback function to a component. This is a small piece of my App.js file
loginCompleted = (status) => {
if (status == "1") {
this.setState({ currentUser: "xxxx" });
}
}
render() {
return (
<BrowserRouter>
<MainTemplate authStatus={ this.state.currentUser }>
<Switch>
<Route exact path='/' component={Home} />
<Route exact path='/login' component={Login} loginCompleted={this.loginCompleted} />
</Switch>
</MainTemplate>
</BrowserRouter>
);
}
As you can see I want to pass the loginCompleted callback to the Login component.
In the Login component there is this function that handle the submit form
handleSubmit = async e => { e.preventDefault(); const token = await this.LoginService.loginUser(this.state.username, this.state.password); if (token) { console.log(token); this.props.loginCompleted(token); this.props.history.push("/home"); } else { console.log("NULL"); } }
I recevice the error
Unhandled Rejection (TypeError): this.props.loginCompleted is not a function
Despite the research I still don't understand why. Can you help me? Thanks!
Upvotes: 0
Views: 115
Reputation: 570
Seems, that you are passing prop to the route, not to the component itself. Try this approach.
loginCompleted = (status) => { if (status == "1") { this.setState({ currentUser: "xxxx" }); } } render() { return ( <BrowserRouter> <MainTemplate authStatus={ this.state.currentUser }> <Switch> <Route exact path='/' component={Home} /> <Route exact path='/login'> <Login loginCompleted={this.loginCompleted} /> </Route> </Switch> </MainTemplate> </BrowserRouter> ); }
We wrap the Component inside of Route and pass the prop to component, not to route.
Upvotes: 1