ReactJs setState callback not working - javascript

I have a strange behavior with the setState callback, hopefully somebody can help. The callback just isn't fired.
Here is what I do:
this.setState(
(prevState, props) => {
return { first: obj, questions: [] }
},
this.changeStateCb
);
For some reason the changeStateCb function is never being called. Same problem when I change it to:
this.setState(
(prevState, props) => {
return { first: obj, questions: [] }
},
() => console.log(this.state)
);
I just updated from v15.x to 16.2.0

Do you have a demo? I just put up a simple working example, and it seems to run just fine under React 16.2.0. Do note though that the optional callback should be used sparingly. As the docs mention, it will be executed once setState is completed and the component is re-rendered. So, a better place to do the logic in this.changeStateCb would be inside componentDidUpdate.

I just had the same issue happen to me. A simple console.log('test') in the callback wouldn't even run. It turns out I had to delete my /dist folder in the build directory. I am using Type Script and webpack and upgraded from a .net core template.

Have the same issue. The callback is not invoked. I traced it to React min code and the function to enqueueSetState does not accept the callback even though it is passed in from internal React code...so code explains why it is not called. But this used to work just fine in React 15.x - what's going on...I am trying React 16.8.4

Related

react js variable update delay - react.js [duplicate]

I'm reading Forms section of reactjs documentation and just tried this code to demonstrate onChange usage (JSBIN).
var React= require('react');
var ControlledForm= React.createClass({
getInitialState: function() {
return {
value: "initial value"
};
},
handleChange: function(event) {
console.log(this.state.value);
this.setState({value: event.target.value});
console.log(this.state.value);
},
render: function() {
return (
<input type="text" value={this.state.value} onChange={this.handleChange}/>
);
}
});
React.render(
<ControlledForm/>,
document.getElementById('mount')
);
When I update the <input/> value in the browser, the second console.log inside the handleChange callback prints the same value as the first console.log, Why I can't see the result of this.setState({value: event.target.value}) in the scope of handleChange callback?
From React's documentation:
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.
If you want a function to be executed after the state change occurs, pass it in as a callback.
this.setState({value: event.target.value}, function () {
console.log(this.state.value);
});
As mentioned in the React documentation, there is no guarantee of setState being fired synchronously, so your console.log may return the state prior to it updating.
Michael Parker mentions passing a callback within the setState. Another way to handle the logic after state change is via the componentDidUpdate lifecycle method, which is the method recommended in React docs.
Generally we recommend using componentDidUpdate() for such logic instead.
This is particularly useful when there may be successive setStates fired, and you would like to fire the same function after every state change. Rather than adding a callback to each setState, you could place the function inside of the componentDidUpdate, with specific logic inside if necessary.
// example
componentDidUpdate(prevProps, prevState) {
if (this.state.value > prevState.value) {
this.foo();
}
}
You could try using ES7 async/await. For instance using your example:
handleChange: async function(event) {
console.log(this.state.value);
await this.setState({value: event.target.value});
console.log(this.state.value);
}
Watch out the react lifecycle methods!
http://projects.wojtekmaj.pl/react-lifecycle-methods-diagram/
https://reactjs.org/docs/react-component.html
I worked for several hours to find out that getDerivedStateFromProps will be called after every setState().
😂
Sometime this issue occurs with state.
In case of hooks, you should use useEffect hook, As below-
const [fruit, setFruit] = useState('');
setFruit('Apple');
useEffect(() => {
console.log('Fruit', fruit);
}, [fruit])
This saved my day, Hope will help you!!!
Accessing this.state after calling the setState method is not guaranteed to return the updated status due to the asynchronous nature of setState.
To guarantee an update after calling setState, there are two solutions you may pursue.
Solution 1: As mentioned in one of the above answers, put your code in the componentDidUpdate method
Solution 2: As mentioned in another of the above answers, pass your stuff as a callback
this.setState({value: myValue}, function () {
this.functionThatIsExecutedWhenStateIsUpdated();
});
It's important to note that these two solutions are not clearly interchangeable. The one cannot easily solve all the use-cases of the other. As a general rule, if you can, best practice says that solution 1 is preferred. But, there are use-cases where only solution 2 "more effectively" works such as the "update-my-view-and-post-my-data" use case. This use case goes like this:
After adding an item, say, "Add Schedule", I want to both add that item to a front-end list and immediately post the just-updated-list to the backend, as demonstrated in the concept below:
If you dont do either solution, i.e. if you only say this in your code:
addToItemArray = () => {
this.setState{{ scheduledItemsArray: newObjectListWithMax}}
this.postData();
}
<button className="btn btn-secondary btn-block" onClick={this.addToItemArray}>Add Shedule</button>
... you will post the list excluding the "Delivery to Max" item, because the state wont be updated when you this.postData() (again, because its asynchronous).
If you utilise solution 1, you would make a POST after typing in every character in the Schedule Name textbox!
There are other ways aswell to cater for this use-case but solution 2 best conveys the intent when reading the code.
Given the ubiquitous nature of this use case in virtually every web app, the callback technique explained by Michael's answer is an indispensable piece of code in every developers toolkit.
async-await syntax works perfectly for something like the following...
changeStateFunction = () => {
// Some Worker..
this.setState((prevState) => ({
year: funcHandleYear(),
month: funcHandleMonth()
}));
goNextMonth = async () => {
await this.changeStateFunction();
const history = createBrowserHistory();
history.push(`/calendar?year=${this.state.year}&month=${this.state.month}`);
}
goPrevMonth = async () => {
await this.changeStateFunction();
const history = createBrowserHistory();
history.push(`/calendar?year=${this.state.year}&month=${this.state.month}`);
}
React bathces different set state calls so that it can determine what is the most optimal strategy for rerendering the website is going to be.
Imagine you have an application where you have a lot of different components. Perhaps, with one button click you are updating the state in multiple components, not just on the current one. In this case, React does not want to just completely isolate and do all those different updates independently.
React wants to figure out if it can stack all these updates together, maybe there is a more optimal way of updating these components so that it is more performant. This is what React is doing behind the scenes. As a result, set state call is asynchronous call.
Simply putting - this.setState({data: value}) is asynchronous in
nature that means it moves out of the Call Stack and only comes back
to the Call Stack unless it is resolved.
Please read about Event Loop to have a clear picture about Asynchronous nature in JS and why it takes time to update -
https://medium.com/front-end-weekly/javascript-event-loop-explained-4cd26af121d4
Hence -
this.setState({data:value});
console.log(this.state.data); // will give undefined or unupdated value
as it takes time to update.
To achieve the above process -
this.setState({data:value},function () {
console.log(this.state.data);
});

React useCallback setting dependency on a function called inside the callback

I'm working on a web app using react and saw this implemented there. It goes something like this:
const onAddNewAccount = useCallback(async () => {
await refetch();
setOtherState((prev) => {...});
},
[refetch]);
I don't understand why do this, is this actually something correct? Because from what I understand the callback will be called on one of the dependencies changing.
From what I've seen calling refetch won't actually trigger useCallback probably because it is just called right? not changed.
So basically I need help understanding why they did this.
the callback will be called on one of the dependencies changing.
No, it won't be called, it will just be recreated. The purpose of useCallback is to memoize the function and reuse it if nothing has changed. In other words, it's trying to make it so onAddNewAccount from render 1 === onAddNewAccount from render 2.
If refetch changes, then the memoization will break and a new function is created. That way the new onAddNewAccount can call the new refetch if needed. If refetch never changes, then that's great: the memoization can last forever then.

Difference between ComponentDidUpdate and SetState callback function

I've done some research about an error I got in my react native app
Warning: An update (setState, replaceState, or forceUpdate) was scheduled from inside an update function. Update functions should be pure, with zero side-effects. Consider using componentDidUpdate or a callback..
I've done research but I still can't understand the difference between them. My theoretical idea is to remove an element from an array of objects, but when I use setState with a callback function I get the error. Can anyone point me in the right direction or show me an example of how I can use componentDidUpdate. The code example below works for now but I feel it could be improved on, and I believe that is why I'm getting my error
Delete_Task = (e) => {
this.setState(prevState => {
const tasks = prevState.daily.filter(task => task.ID !== e);
this.setState({daily: tasks});
})
}
You need to return the new state object instead of calling another setState inside the outer setState callback
change
this.setState({daily: tasks});
To
return {daily: tasks};
// OR
return {...prevState, daily:tasks}

React Hook - Cannot Call Parent Component Dispatch in Child Component onComplete Callback

I've tried several solutions to fix this problem, and none have worked.
I have a third-party library that calls an asynchronous function to load something to render in the DOM.
I have a component that wraps the library for the DOM piece and when it finishes I want to be able to call an onComplete method with it.
Everything works fine. However when I call the onComplete function, and then inside that function is a call to dispatch something to a context it blows up and gives me the
Warning: 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 a useEffect cleanup function.
Code
export function ParentComponent(props: any) {
const dispatch: any = React.useContext(dispatchContext);
const onComplete = React.useCallback(
(data: any) => {
if (dispatch !== null && dispatch !== undefined) {
dispatch({
payload: { new_data: "thing" },
type: dispatchType.UPDATING
});
}
},
[dispatch]
);
return (
<div>
<ChildComponent onComplete={onComplete} />
</div>
);
}
interface IProp {
onComplete?: function;
}
export function ChildComponent(props: IProp) {
React.useEffect(() => {
if (library.is_ready) {
library.load(data).then(
() => {
console.log("Success");
props.onComplete(library);
},
(error: any) => {
console.error("ERROR");
}
);
}
}, [library]);
return <div id="library-dom-element"></div>;
}
If I comment out the dispatch function this won't blow up.
It blows up when the asynchronous function is completed and calls the onComplete function which calls the dispatch
ChildComponent.libary.is_ready → ChildComponent.libary.load → ChildComponent.libary.onComplete → ParentComponent.onComplete → dispatch
I have tried adding useCallback to everything. I have tried using useRef to track an is_mounted variable to determine if the DOM pieces are loading correctly.
I just cannot figure out how to call dispatch on the completion of the third party library.
That's literally it.
Can anyone help or provide guidance on this? I thought I understood how these pieces work together, but I'm missing something.
The application I've been making has been pretty complex.
The bug I provided here is a result of component initialization order that arises because of how I am toggling state.
When I created a delay function to help buffer initialization this resolved the issue for the time being.
Apologies for this question as the design pattern does appear to work, there just needs to be accounting for how your React application's complexity is being managed.
Thank you to everyone who took a look :) <3

Unexplained behaviour from React state Change [duplicate]

I'm reading Forms section of reactjs documentation and just tried this code to demonstrate onChange usage (JSBIN).
var React= require('react');
var ControlledForm= React.createClass({
getInitialState: function() {
return {
value: "initial value"
};
},
handleChange: function(event) {
console.log(this.state.value);
this.setState({value: event.target.value});
console.log(this.state.value);
},
render: function() {
return (
<input type="text" value={this.state.value} onChange={this.handleChange}/>
);
}
});
React.render(
<ControlledForm/>,
document.getElementById('mount')
);
When I update the <input/> value in the browser, the second console.log inside the handleChange callback prints the same value as the first console.log, Why I can't see the result of this.setState({value: event.target.value}) in the scope of handleChange callback?
From React's documentation:
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.
If you want a function to be executed after the state change occurs, pass it in as a callback.
this.setState({value: event.target.value}, function () {
console.log(this.state.value);
});
As mentioned in the React documentation, there is no guarantee of setState being fired synchronously, so your console.log may return the state prior to it updating.
Michael Parker mentions passing a callback within the setState. Another way to handle the logic after state change is via the componentDidUpdate lifecycle method, which is the method recommended in React docs.
Generally we recommend using componentDidUpdate() for such logic instead.
This is particularly useful when there may be successive setStates fired, and you would like to fire the same function after every state change. Rather than adding a callback to each setState, you could place the function inside of the componentDidUpdate, with specific logic inside if necessary.
// example
componentDidUpdate(prevProps, prevState) {
if (this.state.value > prevState.value) {
this.foo();
}
}
You could try using ES7 async/await. For instance using your example:
handleChange: async function(event) {
console.log(this.state.value);
await this.setState({value: event.target.value});
console.log(this.state.value);
}
Watch out the react lifecycle methods!
http://projects.wojtekmaj.pl/react-lifecycle-methods-diagram/
https://reactjs.org/docs/react-component.html
I worked for several hours to find out that getDerivedStateFromProps will be called after every setState().
😂
Sometime this issue occurs with state.
In case of hooks, you should use useEffect hook, As below-
const [fruit, setFruit] = useState('');
setFruit('Apple');
useEffect(() => {
console.log('Fruit', fruit);
}, [fruit])
This saved my day, Hope will help you!!!
Accessing this.state after calling the setState method is not guaranteed to return the updated status due to the asynchronous nature of setState.
To guarantee an update after calling setState, there are two solutions you may pursue.
Solution 1: As mentioned in one of the above answers, put your code in the componentDidUpdate method
Solution 2: As mentioned in another of the above answers, pass your stuff as a callback
this.setState({value: myValue}, function () {
this.functionThatIsExecutedWhenStateIsUpdated();
});
It's important to note that these two solutions are not clearly interchangeable. The one cannot easily solve all the use-cases of the other. As a general rule, if you can, best practice says that solution 1 is preferred. But, there are use-cases where only solution 2 "more effectively" works such as the "update-my-view-and-post-my-data" use case. This use case goes like this:
After adding an item, say, "Add Schedule", I want to both add that item to a front-end list and immediately post the just-updated-list to the backend, as demonstrated in the concept below:
If you dont do either solution, i.e. if you only say this in your code:
addToItemArray = () => {
this.setState{{ scheduledItemsArray: newObjectListWithMax}}
this.postData();
}
<button className="btn btn-secondary btn-block" onClick={this.addToItemArray}>Add Shedule</button>
... you will post the list excluding the "Delivery to Max" item, because the state wont be updated when you this.postData() (again, because its asynchronous).
If you utilise solution 1, you would make a POST after typing in every character in the Schedule Name textbox!
There are other ways aswell to cater for this use-case but solution 2 best conveys the intent when reading the code.
Given the ubiquitous nature of this use case in virtually every web app, the callback technique explained by Michael's answer is an indispensable piece of code in every developers toolkit.
async-await syntax works perfectly for something like the following...
changeStateFunction = () => {
// Some Worker..
this.setState((prevState) => ({
year: funcHandleYear(),
month: funcHandleMonth()
}));
goNextMonth = async () => {
await this.changeStateFunction();
const history = createBrowserHistory();
history.push(`/calendar?year=${this.state.year}&month=${this.state.month}`);
}
goPrevMonth = async () => {
await this.changeStateFunction();
const history = createBrowserHistory();
history.push(`/calendar?year=${this.state.year}&month=${this.state.month}`);
}
React bathces different set state calls so that it can determine what is the most optimal strategy for rerendering the website is going to be.
Imagine you have an application where you have a lot of different components. Perhaps, with one button click you are updating the state in multiple components, not just on the current one. In this case, React does not want to just completely isolate and do all those different updates independently.
React wants to figure out if it can stack all these updates together, maybe there is a more optimal way of updating these components so that it is more performant. This is what React is doing behind the scenes. As a result, set state call is asynchronous call.
Simply putting - this.setState({data: value}) is asynchronous in
nature that means it moves out of the Call Stack and only comes back
to the Call Stack unless it is resolved.
Please read about Event Loop to have a clear picture about Asynchronous nature in JS and why it takes time to update -
https://medium.com/front-end-weekly/javascript-event-loop-explained-4cd26af121d4
Hence -
this.setState({data:value});
console.log(this.state.data); // will give undefined or unupdated value
as it takes time to update.
To achieve the above process -
this.setState({data:value},function () {
console.log(this.state.data);
});

Categories

Resources