Home > Software design >  React | error "Objects are not valid as a React child" when trying to push to state array
React | error "Objects are not valid as a React child" when trying to push to state array

Time:11-19

I'm learning some React with a project I dreamed up that has data being passed via props and also pubsub messages. I'm passing an email address via pubsub and it comes in fine on the pubsub subscribe method, like this:

myEmailChannel.subscribe("email", (msg) => {
            let data = msg.data;
            
            console.log(data);
                         
        });

The above results in a console log of

value: '[email protected]'

[email protected] being a fake test email that I sent via pubsub. The problem happens when I try to add the data to an already initialized state array of "emails", I get some crazy error about "Objects are not valid as a React child (found: object with keys {value}). If you meant to render a collection of children, use an array instead." I am trying something like:

 myEmailChannel.subscribe("email", (msg) => {
            let data = msg.data;
            
            console.log(data);
            let emails = [...this.state.emails];
            emails.push({ value: data });
            this.setState({emails});
            
        });

only to get the aforementioned error. Actually, it happens no matter how I try to add the data to the array. I think I understand that I'm just formatting the incoming data incorrectly for the state array? Any help would be much appreciated.

EDIT: I followed the error a little further and it says the error occurs when it tries to iterate over the array for display:

{this.state.emails.map((email, index) => {
                return (

                    <li key={index}>{email}</li>

                );
            })}

CodePudding user response:

As you mentioned, email is an object. When you do something like this

this.state.emails.map((email, index) => (
  <li key={index}>{email}</li>
))

React gets confused. It doesn't know whether it should treat the email object as a string (which is properly what you are trying to do), or render it as a component.

You can do something like this instead.

this.state.emails.map((email, index) => (
  <li key={index}>{email.value}</li>
))
  • Related