Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

updating objects with setState in React

How can I pass multiple states to setState? Here's an example:

getInitialState: function() {
  return {
    list: [],
    newFilm: {},
    searchWord: '',
    searchDetails: {}
  }
},

componentDidMount: function() {
  this.setState({
    searchDetails:someData,
    newFilm: 'I am first text',
  })
}

The question is:

Is the example syntactically correct ?

like image 721
Kirill Stas Avatar asked Oct 25 '16 21:10

Kirill Stas


People also ask

How do you update setState objects?

To update nested properties in a state object in React: Pass a function to setState to get access to the current state object. Use the spread syntax (...) to create a shallow copy of the object and the nested properties. Override the properties you need to update.

How do you update an array of objects in React state?

To update an array of objects state in React: Use the map() method to iterate over the array. On each iteration, check if a certain condition is met. Update the properties of the object that matches the condition.

How do you update an item in React JS?

We can update an object in React using the setState() method. Every component in React inherits the setState() method from its Base component name Component.


1 Answers

There is no syntax problem with the way you are setting state, but there could be a problem with the way you are initialising you state. You have initialized newFilm as an object state but when you set its state you are giving a string. So suppose you try to render it like {this.state.newFilm} it will throw you an error

Objects are not valid as a React child (found: object with keys {}).

as you can see in the snippet below, since the first time the component is rendered it sees an object where later its only a string.

To fix this try initializing you state newFilm as '' or take prevention when you try to render i.e. check where it contains some data and then only render.

Also I don't see someData defined in your componentDidMount function. You need to define it before you can use it.

var App = React.createClass({
  getInitialState: function() {
  return {
    list: [],
    newFilm: {},
    searchWord: '',
    searchDetails: {}
  }
},

componentDidMount: function() {
  var someData = {'name': 'abc'};
  this.setState({
    searchDetails:someData,
    newFilm: 'I am first text',
  })
},
render: function() {
  console.log(this.state.newFilm);
  return (
    <div>{this.state.newFilm}</div>
  )
}
})

ReactDOM.render(<App/>, document.getElementById('app'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.14.8/react.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.14.8/react-dom.js"></script>
<div id="app"></div>
like image 195
Shubham Khatri Avatar answered Oct 16 '22 20:10

Shubham Khatri