Anonymous Anonymous - 7 months ago 32
Javascript Question

is it possible to set multiple state variables in reactjs?

It is given simple react chat container, which successully grabs data with

LoadConversationInformation
function as following

var ConversationContainer = React.createClass({
LoadConversationInformation: function () {
jQuery.ajax({
url: this.props.getMessageUrl,
dataType: 'json',
cache: false,
success: function (data) {
this.setState({data: data});
}.bind(this),
error: function (xhr, status, err) {
console.error(this.props.url, status, err.toString());
}.bind(this)
});
},
...
render: function () {
var Chat = this.state.data.map(function (message) {
return (
<MessageContainer message={message} key={message.id}/>
);
});
return (
<div>
{Chat}
<MessageForm onMessageSubmit={this.handleMessageSubmit}/>
</div>
);
}
});


It is required to check if in first element of
data
exists some attribute, if so, add it to separate state variable, like this:

...
success: function (data) {
if ('hasContactRequest' in data[0]) {
this.setState({
data: data,
hasContactRequest: data[0].hasContactRequest
});
}
else {
this.setState({data: data});
}
}.bind(this),
error: function (xhr, status, err) {
console.error(this.props.url, status, err.toString());
}.bind(this)
...


To make possible in
ConversationContainer
child check for it and render some element, if it is present, like this:

var MessageContainer = React.createClass({
render: function () {
return (
<li className={(this.props.message.type === 'sender') ? 'sender' : 'receiver'}>
<MessageImage />
<MessageDate date={this.props.message.date}/>
<MessageText text={this.props.message.text}/>
{(this.state.hasContactRequest ? <MessageSendContacts/> : null)}
</li>
);
}
});


Generally chat is working but i cant get no luck of adding this additional state variable, and access it like
this.state.hasContactRequest

got:
Uncaught TypeError: Cannot read property 'hasContactRequest' of null


How to properly do it ?

QoP QoP
Answer

MessageContainer has no state, that's the reason why you are getting that error.

You should pass hasContactRequest as a prop to your MessageContainer

var Chat = this.state.data.map(function (message) {
            return (
                <MessageContainer hasContactRequest={this.state.hasContactRequest} message={message} key={message.id}/>
            );
        });

and use it

 var MessageContainer = React.createClass({
        render: function () {
            return (
                <li className={(this.props.message.type === 'sender') ? 'sender' : 'receiver'}>
                    <MessageImage />
                    <MessageDate date={this.props.message.date}/>
                    <MessageText text={this.props.message.text}/>
                    {(this.props.hasContactRequest ? <MessageSendContacts/> : null)}
                </li>
            );
        }
    });
Comments