In a react component, I update state in various ways, but I would like to do an evaluation (call a function) after the state was updated.
When I do the following, secondUpdate() does not access to the updated state, so it is one cycle late:
firstUpdate = e => {
this.setState({ email: e.state.value });
// ... some validation
secondUpdate();
}
secondUpdate() {
const allValid= this.state.aIsValid & this.state.bIsValid & this.state.cIsValid;
this.setState({ allIsValid: allValid });
}
How should I bind secondUpdate() to any or some state update?
You can use setState callback :
this.setState({ email: e.state.value } , () => {
// Will get called once the state is updated
// ... some valdidations
secondUpdate();
});
allIsValid shall not be a state at all. By having states that depend on each other, you risk that states get out of sync, and your logic breaks. Instead, as allIsValid is derived from other states, it can just be calculated based on the state inside render:
render() {
const { email } = this.state;
const allIsValid = email.length > 5 && /*...*/;
// ...
}
You can use componentDidUpdate().
componentDidUpdate(prevProps, prevState){
// code from secondUpdate()
}
Here is official doc
You might like to go through this:
https://reactjs.org/docs/state-and-lifecycle.html#state-updates-may-be-asynchronous
Because this.props and this.state may be updated asynchronously, you
should not rely on their values for calculating the next state.
To fix it, use a second form of setState() that accepts a function
rather than an object. That function will receive the previous state
as the first argument, and the props at the time the update is applied
as the second argument:
this.setState({
// change the state
}, () => {
//Perform something after the state is updated.
})
Related
Being new to react, I saw a similar example but they were not clearly explained and I didn't understand how to solve this problem. I have an API, the new data is posted to the API.
ComponentDidMount() will initiate the data from the API first time.
I went through the documentation and saw that componentDiUpdate() will always re-render the page if the new data is added.
This is my code so far:
constructor(props){
super(props);
this.state = {
newData: [],
dataApi: this.props.getAllData() //method that is using GET_ALL_DATA actions/reducers using fetch(get)
}
}
// it gets the data
componentDidMount() {
this.state.dataApi
}
componentDidUpdate(prevProps, prevState){
this.state.dataApi.then(data => {
if(prevProps.data != this.props.data) {
this.setState({newData: data});
}
}
}
ComponentDidUpdate() errors:
Can't perform a React state update on an unmounted component. This is a no-op, but it indicates a memory leak in your application. To fix, cancel all subscriptions and asynchronous tasks in the componentWillUnmount method.
How can I fix this problem? by getting the new data from the API when someone makes a post request? Thanks
Solved the problem, thanks everyone:
Solution to the problem will be:
this.state = {
allData: [],
isSubmitted: false
}
async componentDidUpdate(prevProps, prevState){
if(this.mounted && this.state.isSubmitted){
const allData = await this.props.getAllData();
this.setState({isSubmitted: false,
allData: allData.data })
}
componentDidMount(){
this.mounted=true
}
componentWillUnmount() {
this.mounted = false;
}
functionAddDataToApi(){
// some logic
this.setState({isSubmitted: true})
}
The componentDidMount() lifecycle method gets called once only when your component is rendered for the first time.
In your constructor(), you don't need to put a promise on your state. Instead you can remove dataApi and just call the method directly. In componentDidMount(), you'll make your API call. When the API call has finished, you can use this.setState().
The componentDidUpdate method gets called every time one of your prop or state values gets updated. As such, it is a bad idea to update state within it as you risk infinitely looping.
constructor(props){
super(props);
this.state = {
newData: [],
};
}
// it gets the data
componentDidMount() {
this.props.getAllData().then(data => {
this.setState({
newData: data,
});
});
}
if you want to hook to props change before re-render try hooking into componentWillReceiveProps. componentWillReceiveProps will update state synchronously.
also.. code in your componentDidMount will do nothing :)
// it gets the data
componentDidMount(){
this.state.dataApi}
try to replace it with
// it gets the data
componentDidMount() {
this.state.dataApi.then(data => {
this.setState({
newData: data,
});
});
}
When setting the state asynchronously (for example, after a promise is resolved), it's important to make sure that your component is still mounted, otherwise, you risk setting the state on an unmounted component (which triggers the error that you are getting).
To do that, you will need to set some kind of a flag (like this.mounted in the below example):
componentDidMount() {
this.mounted = true;
}
async componentDidUpdate() {
const data = await someAPICall();
if (this.mounted && !_.isEqual(this.state.data, data)) { // See comment below
this.setState({data});
}
}
componentWillUnmount() {
this.mounted = false;
}
Also, when comparing the old data with the new data, you'll need to perform a deep compare (in the example above I'm using lodash isEqual(...)).
A shallow compare (i.e. this.state.data !== data) compares the references of each of the objects, which are always going to be different, regardless of the actual data, and therefore will run into an infinite loop because setState() will trigger another componentDidUpdate() and so on.
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.
I need to use current props and previous props value in my React component.
So i did it like this
state = {
current: null,
previous: null,
};
componentWillReceiveProps(nextProps) {
if (nextProps.amount !== this.state.current) {
this.setState({previous: this.state.current, current: nextProps.amount});
}
}
...
render() {
const {previous, current} = this.state;
return (
...
<CountUp className="counter" start={previous} end={current} duration={1}/>
...
)
}
It works fine, but is it good React practise to do it like this? Are there others "good" ways to do it?
As of v16.2.0, componentWillReceiveProps is the right place to update state, based on prop changes and since you want to use both current state and previous state in render, you need to maintain, two different state variables as you are doing
However, when you update the state based on previous state, use functional setState method
Check this answer for more details
When to use functional setState
componentWillReceiveProps(nextProps) {
if (nextProps.amount !== this.state.current) {
this.setState(prevState => ({ previous: prevState.current, current: nextProps.amount }));
}
}
According to the latest RFC to React
State derived from props/state
The purpose of this pattern is to calculate some values derived from props for use during render.
Typically componentWillReceiveProps is used for this, although if the calculation is fast enough it could just be done in render.:
From v16.3.0 onwards, you would make use of
static getDerivedStateFromProps(nextProps, prevState) {
if (
!prevState ||
prevState.current !== nextProps.amount
) {
return {
previous: prevState.current,
current: nextProps.amount
};
}
}
I'd like to update this answer for anyone else who comes here from Google. As of v16.8.6, componentWillReceiveProps has been marked as legacy, and is not recommended to use. Instead you should use componentDidUpdate and update your state based on the new props and previous props/previous state.
componentDidUpdate(prevProps, prevState) {
if (this.props.someVal !== prevState.someVal) {
this.setState({ previous: prevState.someVal, current: this.props.someVal });
}
}
Obviously, whether you check the previous state or the previous props is up to your discretion/situation. You can implement componentDidUpdate with or without the parameters, but if you want prevState you must declare prevProps.
React Update Lifecycle
componentDidUpdate()
You can use an arrow function in your setState object.
Like this :
this.setState((prevState) => {
return { yourState: prevState.yourState }
})
prevState is a default name but you can replace the name as you want
I have nested form objects but I try to setState using one handler, somehow doesn't work
constructor() {
super()
this.state = {
form: {
name: '',
location: ''
}
}
}
handleFormInput = (event) => {
this.setState({
[this.state.form[event.target.name]]: event.target.value
})
setTimeout(() => {
console.log(this.state.form)
},50)
}
event.target.name can be name and location.
You cannot directly access and modify a dynamic state within the setState function, you would rather get a copy of the state object and modify it. Also as you may already know that setState is async and hence you have a setTimeout function which is not necessary since setState provides you a callback function which is executed when state has changed.
handleFormInput = (event) => {
var form = {...this.state.form}
form[event.target.name] = event.target.value;
this.setState({
form
}, () => {this.state.form})
}
I think this code is not working properly:
this.setState({
[this.state.form[event.target.name]]: event.target.value
})
alternative is :
handleFormInput = (event) => {
//New code
let obj = {}
obj[this.state.form[event.target.name]] = event.target.value
this.setState(obj,() => { console.log(this.state.form) })
}
to view updated state, use callback function param of this.setState
setState is asynchronous, your state will properly update somehow after the call. Then render will be called again. Try checking your new state in render or in componentWillUpdate : https://facebook.github.io/react/docs/react-component.html#componentwillupdate
You should never look for a change in your state right after changing your state
I have the following state:
this.setState({ selected: { id: 1, name: 'Foobar' } });
Then I update the state:
this.setState({ selected: { name: 'Barfoo' }});
Since setState is suppose to merge I would expect it to be:
{ selected: { id: 1, name: 'Barfoo' } };
But instead it eats the id and the state is:
{ selected: { name: 'Barfoo' } };
Is this expected behavior and what's the solution to update only one property of a nested state object?
I think setState() doesn't do recursive merge.
You can use the value of the current state this.state.selected to construct a new state and then call setState() on that:
var newSelected = _.extend({}, this.state.selected);
newSelected.name = 'Barfoo';
this.setState({ selected: newSelected });
I've used function _.extend() function (from underscore.js library) here to prevent modification to the existing selected part of the state by creating a shallow copy of it.
Another solution would be to write setStateRecursively() which does recursive merge on a new state and then calls replaceState() with it:
setStateRecursively: function(stateUpdate, callback) {
var newState = mergeStateRecursively(this.state, stateUpdate);
this.replaceState(newState, callback);
}
Immutability helpers were recently added to React.addons, so with that, you can now do something like:
var newState = React.addons.update(this.state, {
selected: {
name: { $set: 'Barfoo' }
}
});
this.setState(newState);
Immutability helpers documentation.
Since many of the answers use the current state as a basis for merging in new data, I wanted to point out that this can break. State changes are queued, and do not immediately modify a component's state object. Referencing state data before the queue has been processed will therefore give you stale data that does not reflect the pending changes you made in setState. From the docs:
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.
This means using "current" state as a reference in subsequent calls to setState is unreliable. For example:
First call to setState, queuing a change to state object
Second call to setState. Your state uses nested objects, so you want to perform a merge. Before calling setState, you get current state object. This object does not reflect queued changes made in first call to setState, above, because it's still the original state, which should now be considered "stale".
Perform merge. Result is original "stale" state plus new data you just set, changes from initial setState call are not reflected. Your setState call queues this second change.
React processes queue. First setState call is processed, updating state. Second setState call is processed, updating state. The second setState's object has now replaced the first, and since the data you had when making that call was stale, the modified stale data from this second call has clobbered the changes made in the first call, which are lost.
When queue is empty, React determines whether to render etc. At this point you will render the changes made in the second setState call, and it will be as though the first setState call never happened.
If you need to use the current state (e.g. to merge data into a nested object), setState alternatively accepts a function as an argument instead of an object; the function is called after any previous updates to state, and passes the state as an argument -- so this can be used to make atomic changes guaranteed to respect previous changes.
I didn't want to install another library so here's yet another solution.
Instead of:
this.setState({ selected: { name: 'Barfoo' }});
Do this instead:
var newSelected = Object.assign({}, this.state.selected);
newSelected.name = 'Barfoo';
this.setState({ selected: newSelected });
Or, thanks to #icc97 in the comments, even more succinctly but arguably less readable:
this.setState({ selected: Object.assign({}, this.state.selected, { name: "Barfoo" }) });
Also, to be clear, this answer doesn't violate any of the concerns that #bgannonpl mentioned above.
Preserving the previous state based on #bgannonpl answer:
Lodash example:
this.setState((previousState) => _.merge({}, previousState, { selected: { name: "Barfood"} }));
To check that it's worked properly, you can use the second parameter function callback:
this.setState((previousState) => _.merge({}, previousState, { selected: { name: "Barfood"} }), () => alert(this.state.selected));
I used merge because extend discards the other properties otherwise.
React Immutability example:
import update from "react-addons-update";
this.setState((previousState) => update(previousState, {
selected:
{
name: {$set: "Barfood"}
}
});
As of right now,
If the next state depends on the previous state, we recommend using
the updater function form, instead:
according to documentation https://reactjs.org/docs/react-component.html#setstate, using:
this.setState((prevState) => {
return {quantity: prevState.quantity + 1};
});
My solution for this kind of situation is to use, like another answer pointed out, the Immutability helpers.
Since setting the state in depth is a common situation, I've created the folowing mixin:
var SeStateInDepthMixin = {
setStateInDepth: function(updatePath) {
this.setState(React.addons.update(this.state, updatePath););
}
};
This mixin is included in most of my components and I generally do not use setState directly anymore.
With this mixin, all you need to do in order to achieve the desired effect is to call the function setStateinDepth in the following way:
setStateInDepth({ selected: { name: { $set: 'Barfoo' }}})
For more information:
On how mixins work in React, see the official documentation
On the syntax of the parameter passed to setStateinDepth see the Immutability Helpers documentation.
I am using es6 classes, and I ended up with several complex objects on my top state and was trying to make my main component more modular, so i created a simple class wrapper to keep the state on the top component but allow for more local logic.
The wrapper class takes a function as its constructor that sets a property on the main component state.
export default class StateWrapper {
constructor(setState, initialProps = []) {
this.setState = props => {
this.state = {...this.state, ...props}
setState(this.state)
}
this.props = initialProps
}
render() {
return(<div>render() not defined</div>)
}
component = props => {
this.props = {...this.props, ...props}
return this.render()
}
}
Then for each complex property on the top state, i create one StateWrapped class. You can set the default props in the constructor here and they will be set when the class is initialised, you can refer to the local state for values and set the local state, refer to local functions, and have it passed up the chain:
class WrappedFoo extends StateWrapper {
constructor(...props) {
super(...props)
this.state = {foo: "bar"}
}
render = () => <div onClick={this.props.onClick||this.onClick}>{this.state.foo}</div>
onClick = () => this.setState({foo: "baz"})
}
So then my top level component just needs the constructor to set each class to it's top level state property, a simple render, and any functions that communicate cross-component.
class TopComponent extends React.Component {
constructor(...props) {
super(...props)
this.foo = new WrappedFoo(
props => this.setState({
fooProps: props
})
)
this.foo2 = new WrappedFoo(
props => this.setState({
foo2Props: props
})
)
this.state = {
fooProps: this.foo.state,
foo2Props: this.foo.state,
}
}
render() {
return(
<div>
<this.foo.component onClick={this.onClickFoo} />
<this.foo2.component />
</div>
)
}
onClickFoo = () => this.foo2.setState({foo: "foo changed foo2!"})
}
Seems to work quite well for my purposes, bear in mind though you can't change the state of the properties you assign to wrapped components at the top level component as each wrapped component is tracking its own state but updating the state on the top component each time it changes.
Solution
Edit: This solution used to use spread syntax. The goal was make an object without any references to prevState, so that prevState wouldn't be modified. But in my usage, prevState appeared to be modified sometimes. So, for perfect cloning without side effects, we now convert prevState to JSON, and then back again. (Inspiration to use JSON came from MDN.)
Remember:
State updates are shallow: they only go one level deep
State shouldn't be directly mutated. Instead, use setState(prevState => stateChange)
Steps
Make a copy of the root-level property of state that you want to change
Mutate this new object
Create an update object
Return the update
Steps 3 and 4 can be combined on one line.
Example
this.setState(prevState => {
var newSelected = JSON.parse(JSON.stringify(prevState.selected)) //1
newSelected.name = 'Barfoo'; //2
var update = { selected: newSelected }; //3
return update; //4
});
Simplified example:
this.setState(prevState => {
var selected = JSON.parse(JSON.stringify(prevState.selected)) //1
selected.name = 'Barfoo'; //2
return { selected }; //3, 4
});
This follows the React guidelines nicely. Based on eicksl's answer to a similar question.
ES6 solution
We set the state initially
this.setState({ selected: { id: 1, name: 'Foobar' } });
//this.state: { selected: { id: 1, name: 'Foobar' } }
We are changeing a property on some level of the state object:
const { selected: _selected } = this.state
const selected = { ..._selected, name: 'Barfoo' }
this.setState({selected})
//this.state: { selected: { id: 1, name: 'Barfoo' } }
React state doesn't perform the recursive merge in setState while expects that there won't be in-place state member updates at the same time. You either have to copy enclosed objects/arrays yourself (with array.slice or Object.assign) or use the dedicated library.
Like this one. NestedLink directly supports handling of the compound React state.
this.linkAt( 'selected' ).at( 'name' ).set( 'Barfoo' );
Also, the link to the selected or selected.name can be passed everywhere as a single prop and modified there with set.
have you set the initial state?
I'll use some of my own code for example:
getInitialState: function () {
return {
dragPosition: {
top : 0,
left : 0
},
editValue : "",
dragging : false,
editing : false
};
}
In an app I'm working on, this is how I've been setting and using state. I believe on setState you can then just edit whatever states you want individually I've been calling it like so:
onChange: function (event) {
event.preventDefault();
event.stopPropagation();
this.setState({editValue: event.target.value});
},
Keep in mind you have to set the state within the React.createClass function that you called getInitialState
I use the tmp var to change.
changeTheme(v) {
let tmp = this.state.tableData
tmp.theme = v
this.setState({
tableData : tmp
})
}