1

I am new at React-Native. I just keep getting same error that "Cannot read property 'navigate' of undefined". Here is the sample code

export default class Form extends Component {
    constructor(props) {
        super(props);
        this.loginHandler = this.loginHandler.bind(this);
        this.navigate  = this.props.navigation;
        this.successCallback = this.successCallback.bind(this);
        this.state = {
            email: '',
            password: '',
        }
    }

    // TODO - Login Authentication
    loginHandler() {
        var loginUrl = 'someURL';
        fetch(loginUrl, {
            method: 'POST',
            headers: {
                Accept: 'application/json',
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({
                username: this.state.email,
                password: this.state.password
            }),
        })
            .then(response => { return response.json(); })
            .then(responseData => { return responseData; })
            .then((responseData) => {
                this.successCallback(responseData.token)
            })
            .catch((err) => { console.log(err); });

    }

    successCallback(token) {
        if (token === undefined)
            alert("Email or password is incorrect !");
        else {
            this.props.navigation.navigate('User', {tokenFromUser: token});
        }

}

In successCallback function, if token is generated it means login credentials are correct so it should navigate to UserScreen with paremeter 'token'. Can anyone help me ?

Here is the how I call loginHandler function

        <TouchableOpacity style={styles.button} onPress={this.loginHandler} >
            <Image source={loginImage} style={styles.image} />
            <View style={styles.SeparatorLine} />
            <Text style={styles.text}>
                Enter
            </Text>
        </TouchableOpacity>
3
  • Is your Form registered for navigation? Commented Sep 14, 2018 at 6:32
  • Yes. I also tried that. In my App.js file , I have added Form.js. However I am using this Form.js as component not as screen Commented Sep 14, 2018 at 6:35
  • If your Form.js is a component try using the hoc wrapper for navigation as this or pass the navigation props from parent file Commented Sep 14, 2018 at 6:48

1 Answer 1

2

Well I found the solution I guess. Where I call the Form.js component, I simply added {...this.props} as props.

<Form {...this.props}   />

Like this because props of Form.js was empty.

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

Comments

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.