Home > Net >  Objects are not valid as a React child (...) If you meant to render a collection of children, use an
Objects are not valid as a React child (...) If you meant to render a collection of children, use an

Time:03-08

I'm trying to create in React a counter that tracks how many images are submitted by a user. However, when submitting, React crashes and throws this error:

Error: Objects are not valid as a React child (found: object with keys {entries}). If you meant to render a collection of children, use an array instead.
  93 |   })
  94 |     .then(response => response.json())
  95 |     .then(count => {
> 96 |       this.setState(Object.assign(this.state.user, {entries: count}))
     | ^  97 |     })
  98 | }

App.js function to where the error pointed:

onButtonSubmit = () => {
    this.setState({imageUrl: this.state.input});
    app.models
      .predict(
        Clarifai.FACE_DETECT_MODEL,
        this.state.input)
      .then(response => {
        if (response) {
          fetch('http://localhost:3000/image', {
          method: 'put',
          headers: {'Content-Type': 'application/json'},
          body: JSON.stringify({
            id: this.state.user.id
          })
        })
          .then(response => response.json())
          .then(count => {
            this.setState(Object.assign(this.state.user, {entries: count}))
          })
      }
      this.displayFaceBox(this.calculateFaceLocation(response))
      })
      .catch(err => console.log(err));
      }

Entries.js component where the number counter is displayed:

const Entries = ({ name, entries }) => {
  return (
    <div>
      <div className='white f3'>
        {`${name}, your current entry count is...`}
      </div>
      <div className='white f1'>
          {entries}
      </div>
    </div>
  );
}

Interestingly, the counter correctly updates in the PostgreSQL database, and upon second login, the correct number is displayed. However, when submitting another image, the app crashes before updating the counter.

Server.js code:

app.put('/image', (req, res) => {
    const { id } = req.body;
    knex('users').where('id', '=', id)
    .increment('entries', 1)
    .returning('entries')
    .then(entries => {
        res.json(entries);
    })
    .catch(err => res.status(400).json('Unable to get entries'));
})

Anyone can help? Thanks in advance!

CodePudding user response:

I think it is maybe in the way you assign the new 'entries' value in your setState. state updater provides a callback pattern which returns you the previous state which you can use to update the current state.

this.setState((prevState) => {...prevState, entries: count})

Ensure yourself to have an initial state. Some docs here

CodePudding user response:

Got it solved. I had to simply pass count without curly brackets: this.setState(Object.assign(this.state.user, count))

  • Related