Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting an error after using setState with a promise

Tags:

Code:

onDragEnd = {     (event) => this.setState({ playerMarkerPositionFuture: event.nativeEvent.coordinate })     .then(() => alert("hello")) } 

When the following code gets executed I receive this error:

undefined is not an object evaluating ('_this.setState({playerMarkerPositionFuture: event.nativeEvent.coordinate}).then') 

If I remove the promise everything works as expected so it means that most likely I used the promise in a wrong way:

onDragEnd={     (event) => this.setState({ playerMarkerPositionFuture: event.nativeEvent.coordinate }) }  
like image 424
dclipca Avatar asked May 09 '19 11:05

dclipca


People also ask

Can I setState in Promise?

To update the state of a component, you use the setState method. However it is easy to forget that the setState method is asynchronous, causing tricky to debug issues in your code. The setState function also does not return a Promise. Using async/await or anything similar will not work.

Does setState hook return a Promise?

Even though they are asynchronous, the useState and setState functions do not return promises. Therefore we cannot attach a then handler to it or use async/await to get the updated state values.

What happens after setState is called?

It ensures that the component has been updated and calls for re-rendering of the component. setState is asynchronous call means if synchronous call get called it may not get updated at right time like to know current value of object after update using setState it may not get give current updated value on console.

How do I dispatch after setState?

When the custom setState method is called with a callback argument, we will push that callback into an array and save it to a ref. Next we write a useEffect hook that will be called after React has finished committing any state changes.


1 Answers

setState accepts a callback, but it doesn't return a promise. See docs

Calls to setState are asynchronous - don’t rely on this.state to reflect the new value immediately after calling setState. Pass an updater function instead of an object if you need to compute values based on the current state (see below for details).

(event) => {     this.setState({playerMarkerPositionFuture: event.nativeEvent.coordinate }, () => alert("hello")); } 
like image 55
Raulucco Avatar answered Oct 04 '22 10:10

Raulucco