Statement is not being reached after setting State in react ES-6 - reactjs

In this react code i am trying to set the data to current state,After setting the data to state i need to use it in fixed data table.To achieve it, i wrote as below.The main issue is that the statement next to "this.setState" in componentDidMount is not being executed/reached where i need to call data table function there.
here is my code:
export default class Main extends React.Component {
constructor(props) {
super(props);
this.state = {
result: [],
loading: false,
filteredRows: null,
filterBy: null,
};
}
getZipData() {
//Here i got the data from server
}
componentDidMount() {
this.getZipData().then((data)=>{
console.log("data:"+data.length);
this.setState({result:data,loading:true}); //state successfully set here.
console.log("result:*******************"+this.state.result.length); //this console is not printed
this._filterRowsBy(this.state.filterBy)
});
};
_rowGetter(rowIndex){
alert("row Getter");
return this.state.filteredRows[rowIndex];
}
_filterRowsBy(filterBy){
var rows = this.state.result.slice();
var filteredRows = filterBy ? rows.filter((row)=>{
return row.RecNo.toLowerCase().indexOf(filterBy.toLowerCase()) >= 0
}) : rows;
this.setState({
filterRows,
filterBy,
})
}
_onFilterChange(e){
this._filterRowsBy(e.target.value);
}
render() {
if(this.state.loading==false) {
return (
<div className="row-fluid">
<img className="col-sm-6 col-sm-offset-3 col-xs-6 col-xs-offset-3"
src="http://www.preciseleads.com/images/loading_animation.gif"/>
</div>
)
}
else{
console.log("result:////////////////////"+this.state.result.length); //this console is printed
console.log("loading completed");
return(
<div>
<!-- fixed data table code goes here -->
</div>
)
}
}
}
state is successfully updated but after that statement is not reached, IN componentDidMount,
any help much appreciated.

Add a catch handler to your Promise. I suppose you are getting an error.

Hi there maybe this is your problem,
Facebook:
setState() does not immediately mutate this.state but creates a
pending state transition. Accessing this.state after calling this
method can potentially return the existing value. There is no
guarantee of synchronous operation of calls to setState and calls may
be batched for performance gains. setState() will always trigger a
re-render unless conditional rendering logic is implemented in
shouldComponentUpdate(). If mutable objects are being used and the
logic cannot be implemented in shouldComponentUpdate(), calling
setState() only when the new state differs from the previous state
will avoid unnecessary re-renders.
this.setState({result:data,loading:true}, () => {
// Your logic
});
the second argument is a callback function which is called after the state is set.
Hope this helps:)
Edit: i didn't see the invariant error, (From the comment, could u provide the full error)

Related

componentWillReceiveProps seems to be called twice

In my react project, the componentWillReceiveProps() function seems to be called twice, but not sure what the problem is.
Here is the code.
import React, { Component, PropTypes } from 'react';
...
class MessagesList extends Component {
constructor(props) {
super(props);
this.state = {
message: '',
messages: []
};
...
componentWillMount() {
this.props.init_message();
};
componentWillReceiveProps(nextProps) {
this.setState({
messages: this.props.user.messages
});
var msgs = this.props.user.messages;
var total_group = [];
var msg_group = [];
var group_date = 0;
setTimeout(() => {
if (typeof msgs != 'undefined') {
for(var i = 0; i < msgs.length; i++) {
...
}
}
}, 100);
};
render() {
return (
<div className="row">
<div className="col-12">
<div className="messages">
{this.state.messages.map(message => {
return (
<div>{message.user}: {message.message} : {message.date}</div>
)
})}
</div>
</div>
...
</div>
);
}
}
I was going to read the msgs.length in the componentWillReceiveProps(), I got the following issue.
msgs.length is undefiend
After that I got the values of array, so I think the componentWillReceiveProps() seems to be called twice. So in the first call, can't read the value and then in the second call, read the value at least.
Please help me.
componentWillReceiveProps is invoked before a mounted component receives new props. If you need to update the state in response to prop changes (for example, to reset it), you may compare this.props and nextProps and perform state transitions using this.setState() in this method.
Note that if a parent component causes your component to re-render, this method will be called even if props have not changed. Make sure to compare the current and next values if you only want to handle changes.
You will get the details from react docs.
ComponentWillReceiveProps is a method from the growth/update phase of the React lifecycle.
The Growth phase is triggered in three different ways: changing of props, changing of state or calling forceUpdate().
The value you are referring to in componentWillReceiveProps, this.props.user.messages, is the current value not the nextProps value.
Also something to consider is that the setState method is actually an asynchronous function. So when that setting of state takes place, it will cause another rerender.
I suspect, but I cannot be sure without more of your code, that setState is called once with your original value from props which triggers another update cycle. During this next update cycle the setState method now sets state to the new prop values.
Are you perhaps meaning to use nextProps.user.messages instead of this.props.user.messages?

console not showing updated values after setState [duplicate]

Ok, i'll try and make this quick because it SHOULD be an easy fix...
I've read a bunch of similar questions, and the answer seems to be quite obvious. Nothing I would ever have to look up in the first place! But... I am having an error that I cannot fathom how to fix or why its happening.
As follows:
class NightlifeTypes extends Component {
constructor(props) {
super(props);
this.state = {
barClubLounge: false,
seeTheTown: true,
eventsEntertainment: true,
familyFriendlyOnly: false
}
this.handleOnChange = this.handleOnChange.bind(this);
}
handleOnChange = (event) => {
if(event.target.className == "barClubLounge") {
this.setState({barClubLounge: event.target.checked});
console.log(event.target.checked)
console.log(this.state.barClubLounge)
}
}
render() {
return (
<input className="barClubLounge" type='checkbox' onChange={this.handleOnChange} checked={this.state.barClubLounge}/>
)
}
More code surrounds this but this is where my problem lies. Should work, right?
I've also tried this:
handleOnChange = (event) => {
if(event.target.className == "barClubLounge") {
this.setState({barClubLounge: !this.state.barClubLounge});
console.log(event.target.checked)
console.log(this.state.barClubLounge)
}
So I have those two console.log()'s, both should be the same. I'm literally setting the state to be the same as the event.target.checked in the line above it!
But it always returns the opposite of what it should.
Same goes for when I use !this.state.barClubLounge; If it starts false, on my first click it remains false, even though whether the checkbox is checked or not is based off of the state!!
It's a crazy paradox and I have no idea whats going on, please help!
Reason is setState is asynchronous, you can't expect the updated state value just after the setState, if you want to check the value use a callback method. Pass a method as callback that will be get executed after the setState complete its task.
Why setState is asynchronous ?
This is because setState alters the state and causes re rendering. This can be an expensive operation and making it synchronous might leave the browser unresponsive.
Thus the setState calls are asynchronous as well as batched for better UI experience and performance.
From Doc:
setState() does not immediately mutate this.state but creates a
pending state transition. Accessing this.state after calling this
method can potentially return the existing value. There is no
guarantee of synchronous operation of calls to setState and calls may
be batched for performance gains.
Using callback method with setState:
To check the updated state value just after the setState, use a callback method like this:
setState({ key: value }, () => {
console.log('updated state value', this.state.key)
})
Check this:
class NightlifeTypes extends React.Component {
constructor(props) {
super(props);
this.state = {
barClubLounge: false,
seeTheTown: true,
eventsEntertainment: true,
familyFriendlyOnly: false
}
}
handleOnChange = (event) => { // Arrow function binds `this`
let value = event.target.checked;
if(event.target.className == "barClubLounge") {
this.setState({ barClubLounge: value}, () => { //here
console.log(value);
console.log(this.state.barClubLounge);
//both will print same value
});
}
}
render() {
return (
<input className="barClubLounge" type='checkbox' onChange={this.handleOnChange} checked={this.state.barClubLounge}/>
)
}
}
ReactDOM.render(<NightlifeTypes/>, document.getElementById('app'))
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id='app'/>
Since setState is a async function. That means after calling setState state variable does not immediately change. So if you want to perform other actions immediately after changing the state you should use callback method of setstate inside your setState update function.
handleOnChange = (event) => {
let inputState = event.target.checked;
if(event.target.className == "barClubLounge") {
this.setState({ barClubLounge: inputState}, () => { //here
console.log(this.state.barClubLounge);
//here you can call other functions which use this state
variable //
});
}
}
This is by-design due to performance considerations. setState in React is a function guaranteed to re-render Component, which is a costly CPU process. As such, its designers wanted to optimize by gathering multiple rendering actions into one, hence setState is asynchronous.

componentWillReceiveProps infinite loop?

I am new to react and I am wondering if this is normal or not. If I place a console.log in the componentWillReceiveProps method, it just infinitely logs information. I have a if (this.props !== nextProps) {} check right below the console.log so nothing actually fires off but the infinite loop concerned me as a beginner. Can someone please shed some light on if this is normal or not?
I will some of the important snippets from my code.
// From the parent component
constructor(props: any) {
super(props);
this._handleChanged = this._handleChanged.bind(this);
this._onSave = this._onSave.bind(this);
this.state = { columns: {}, fieldsWithErrors: {}, loaded: false, loadedValues: {} };
}
componentDidMount() {
RestUtil.get().then((response) => {
// put in an if statement to check if response came back null
this.state.loadedValues = response;
this.setState({
loadedValues: this.state.loadedValues,
loaded: true
});
}, (error: any) => {
alert(`There was a problem submitting your request: ${error}`);
console.log(error);
});
}
<MyDatePicker
label="Label"
name="Name"
isrequired={false}
onSelectDate={this._handleChanged}
value={this.state.loadedValues["Name"]}
/>
// From MyDatePicker
public render() {
return (
<div>
<DatePicker
label={this.props.label}
strings={DayPickerStrings}
placeholder='Select a date...'
value={this.state.date}
isRequired={this.props.isRequired}
onSelectDate={this._handleChange}
/>
</div>
);
}
There are a few issues here that might be causing what you are seeing.
You should never set state directly outside of the constructor. Doing this.state.value = something in your componentDidMount method is incorrect, as you should never set the state of a React component in any way other than using setState.
You should not read from state in the same method as you set it. React's setState does not change the component's state immediately - state changes are batched, merged together and applied at a later point. If you want to read data from the state when it changes, you should do it in the componentDidUpdate method by comparing old state to new state.
If you try to change your state directly, you'll cause some issues with your component's lifecycle, which might be what is causing the infinite loop. Reading from state right after setting it might also not get you the values you expect.
Try checking out the component lifecycle methods and refactoring your code into something more idiomatic. That might make the problem go away.

Unable to setState to React component

I'm trying to set the state of my PlayerKey component here however the state won't update on a onClick action:
class PlayerKey extends Component {
constructor(props) {
super(props);
this.state = {
activeKeys:[]
}
}
activateKey = (e) => {
this.setState({
activeKeys:["2","3"]
})
}
render() {
return (
<div className="key" data-row-number={this.props.rowKey} data-key-number={this.props.dataKeyNumber} onClick={this.activateKey}></div>
)
}
}
I've tried console logging this.state in activateKey and it gives me the state of the component no problem (the blank array) so not sure why I can't update it?
setState method in react is asynchronous and doesn't reflect the updated state value immediately.
React may batch multiple setState() calls into a single update for performance.
So accessing the recently set state value might return the older value. To see whether the state has really been set or not, You can actually pass a function as callback in setState and see the updated state value. React Docs
As in your case, you can pass a function as callback as follows.
activateKey = (e) => {
this.setState({
activeKeys:["2","3"]
}, () => {
console.log(this.state.activeKeys); // This is guaranteed to return the updated state.
});
}
See this fiddle: JSFiddle

in react can't get new value after immediately setState

I am working with Reactjs. in which I am setting error if not properly entered.
Sample code is:
handleChange: function() {
if(shares) {
this.setState({
error_shares:''
})
}
if(this.state.error_shares === ''){
console.log('entered!!')
}
}
Here value of error_state doesn't reflect changed value in next if
Yes, that is the desired behavior.
The reason why the value has not been updated is because your component has not been re-rendered yet.
If you need such a feature, you should use the componentDidUpdate callback.
See the lifecycle methods here.
EXPLANATION:
Here is how React works:
Each component is a function of external props + internal state
If a change in either of the two is triggered, the component is queued to be re-rendered (it is asynchronous so that the client application is not blocked).
See the above link for exact sequence of operations but here is a little proof of concept.
import React from 'react';
class Example extends React.Component {
constructor(props, context) {
super(props, context);
// initial state
this.state = {
clicked: false
};
}
componentDidUpdate(prevProps, prevState) {
console.log(this.state.clicked); // this will show "true"
}
render() {
return (
<button
onClick={() => {
this.setState({clicked: true});
}}
>
</button>
);
}
}
setState is asynchronous in nature.
The second (optional) parameter is a callback function that will be
executed once setState is completed and the component is re-rendered.
so you can do something like this.
handleChange: function () {
if ( shares ) {
this.setState( {
error_shares: ''
}, function () {
if ( this.state.error_shares === '' ) {
console.log( 'entered!!' )
}
} )
}
}
source: https://facebook.github.io/react/docs/component-api.html#setstate
Yes, indeed.
setState() does not immediately mutate this.state but creates a pending state transition. Accessing this.state after calling this method can potentially return the existing value.
http://facebook.github.io/react/docs/component-api.html
No. You can't get update value in console just after setState. This is because as soon as setState is called, view is re-rendered. Hence to get updated value, you can check it inside render() .
render(){
if(this.state.error_shares === ''){
//your code.
}
}

Resources