0

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!

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Noooooooo! What a stupid mistake:-( Thank you very much!
It happens when you are too tired)) You are welcome!
Thank you for your understanding!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.