4

I am new to React Native and trying to build a Messenger app and I have 2 components Search and Messenger​. I am struggling to pass the data I got from Search to Messenger.

Search component finds user (receiver) and me being sender I want to communicate but after finding user in Search I want to pass that user to Messenger so that I can chat with that specific user that found in <Search> component.

In addition, Search component has Views that will display user calendar etc.. so ideally I don't want to use <Messenger> in render() method of Search as it will include Messenger component features inside the Search component which destroys the purpose of <Search> component.

So my code is :

'use strict';


var Search = React.cerateClasss({

getDefaultProps: function () {
    return {
        date: new Date(),
        singerName:''
    };
},
getInitialState: function () {
    return {
        date: this.props.date,
        artistName: '',
        artistUserId: 1,
        maxNoArtist: 0,
        imagePath: '../common/images/1.png',
        user: null
    }
},
getArtistName: function () {
    var artist = [];
    var query = new Parse.Query(Parse.User);
    query.equalTo('userId', this.state.artistUserId);
    return query.first({
        success: (result) => {
            this.setState({artistName: result.get('name')});
            this.props.singerName= result.get('name');
            this.setState({imagePath: result.get('image').url()});
        },
        error: (data, error) => {
            console.log('Error occured : ' + error.message())
        }
    });
},
render: function () {
    if (!this.state.user) {
        return <View style={styles.container}>
            <Text style={styles.label}> Loading.... </Text>
        </View>
    }
    var username = this.state.user.get('username');


    return (
            <View style={styles.container}>

            <ResponsiveImage source={{uri:this.state.imagePath}} initHeight="200" initWidth="400"/>


            <Text style={styles.label}>
                {this.state.artistName}
            </Text>

            <View style={styles.innerButtonView}>
                <Button text={'Onki'} onPress={this.getPreviousArtistName}/>
                <Button text={'Indiki'} onPress={this.getNextArtistName}/>
            </View>

            <CalendarPicker
                selectedDate={this.state.date}
                onDateChange={this.onDateChange}
                />

            <View style={styles.innerButtonView}>
                <Button text={'Cyk'} onPress={this.onLogoutPress}/>
                <Button text={'Habarlas'} onPress={this.onPress}/>
            </View>

           <Messenger singerName={this.props.singerName}></Messenger> // BREAKS SEARCH COMPONENT PURPOSE - INCLUDES MESSENGER FEATURES IN TO SEARCH COMPONENT

        </View>
    );
},
})


var Messenger = React.createClass({
    getInitialState: function () {
        return {
            greeting: 'Salam',
            date: new Date(),
            errorMessage: '',
            user: null,
            olderMessageTextFrom: [],
            olderMessageTextTo: [],
            olderMessageDateFrom: [],
            olderMessageDateTo: [],
            earlierMessages: []
        }
    },
    componentWillMount: function () {
        Parse.User.currentAsync().then((user) => {
                this.setState({user: user})
            }
        )
    },
    getMessages() {
        return [
            {
                text: this.state.greeting,
                name: this.props.singerName,
                image: require('../common/images/1.png'),
                position: 'left',
                date: new Date()
            },
4
  • I don't really understand your question. You want to pass data from the Messenger component to the Search component ? And what is the error thrown ? Commented Feb 24, 2016 at 9:18
  • Actually it is other way around. I want to pass data from Search to Messenger. I dont get error nor value. Commented Feb 24, 2016 at 9:20
  • OK, and in your example, you don't get the singerName right ? Have you tried to do console.log(this.props.singerName) in your render method of your Search component to see if it is not empty ? Commented Feb 24, 2016 at 9:22
  • Yeah you are right I dont get singerName. Yes I tried console.log(this.props.singerName) and I dont get value. Commented Feb 24, 2016 at 9:28

2 Answers 2

2

I am late to answer but I did in different way using props.

I have two components.

  1. Splash.js
  2. Home.js

I am passing the data (Let's take String) from Splash.js to Home.js.

First component (Sender)

this.props.navigation.navigate('Home', {user_name: userName})

Second component (Receiver)

this.props.navigation.state.params.user_name

Hope this would help you.

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

Comments

1

OK, so based on your infos, I think the issue is that you don't get the singerName in the Messenger component.

First, I'd change your getArtistName method to this :

getArtistName: function () {
    var artist = [];
    var query = new Parse.Query(Parse.User);
    query.equalTo('userId', this.state.artistUserId);
    return query.first({
        success: (result) => {
            this.setState({artistName: result.get('name')});
            // Removed the this.props.singerName = ... 
            this.setState({imagePath: result.get('image').url()});
        },
        error: (data, error) => {
            console.log('Error occured : ' + error.message())
        }
    });
}

then in your render method :

<Messenger singerName={this.state.artistName} />

Inside a component you need to use setState and not change props : that is to say that this.props.singerName = 'singer' is a wrong way of doing things, you should do this.setState({singerName: 'singer'}); then access it with this.state.singerName

Inside your messenger component, you access it with this.props.singerName

7 Comments

Thanks for constructive feedback much appreciated. I have tried above mentioned solution but I have 2 issues. 1. When I add <Messenger singerName={this.state.artistName} /> then all features that live in Messenger component appears on Search page 2. I still dont get singerName in Messenger component.
Updated previous comment to mention 2 issues. Here is the repo to my app : github.com/ckurban/toyagel.git
I edited my answer. Runs fine and I get the artist with this.props.singerName in Messenger component. If you add the component Messenger, it is normal for all features to appear. Maybe add a prop: <Messenger singerName={this.state.singerName} displayFeatures={false} /> and in messenger component check if this.props.displayFeatures is true to display some features.
When you say : you should do this.setState({singerName: 'singer'}); then access it with this.state.singerName Inside your messenger component, you access it with this.props.singerName I thought we do use setState when we are changing state rather than prop, but if I do this.setState({singerName: 'singer'}); then it is changing the singerName prop or do you mean artistName state ?
I am keep getting : 2016-02-24 13:19:41.212 [trace][tid:com.facebook.React.JavaScript] Artist name : undefined
|

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.